我正在学习事件委托,我将点击事件放在主父级上,即缩略图。当我单击底部的图像时,我想将 src 设置为 img class="main" src,但我注意到当我在图像之间单击时,单击缩略图 div 上的其他任何位置,或者按 Tab 然后输入我得到空。我查看了一下,发现我的 event.target 目标是锚标记以及 div 类“缩略图”。我明白为什么,当我将点击事件放在缩略图(父级)上时,但是有没有办法我只能定位 img 标签?
请不要使用 jQuery,我想使用纯 js 来学习这个,谢谢!
function displaySelected() {
const getMainClass = document.querySelector('.main');
const getThumbnails = document.querySelector('.thumbnails');
getThumbnails.addEventListener('click', function(event) {
getMainClass.setAttribute('src', event.target.getAttribute('src'));
console.log(event.target);
});
}
displaySelected();
* {
box-sizing: border-box;
}
main {
min-width: 250px;
padding: 30px;
}
.hero {
height: 200px;
margin-bottom: 20px;
}
.hero img {
height: 100%
}
.thumbnail {
display: inline-block;
cursor: pointer;
height: 60px;
}
a.thumbnail:hover {
box-shadow: 5px 5px 5px gray;
}
.thumbnail img {
max-height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<main role="main">
<h1>Image Carousel</h1>
<div class="hero">
<img class="main" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat1.jpg" alt="An orange-eyed grey cat stretches toward the camera."/>
</div>
<div class="thumbnails">
<a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat1.jpg" alt="An orange-eyed grey cat stretches toward the camera."/></a>
<a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat2.jpg" alt="Closeup of a blue-eyed, grey cat with markings."/></a>
<a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat3.jpg" alt="An orange cat licks its paw."/></a>
<a class="thumbnail" href="#"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-65/cat4.jpg" alt="A content brown cat lounges with eyes closed."/></a>
</div>
慕勒3428872
相关分类