1 回答
TA贡献1848条经验 获得超6个赞
event listener您每次调用时都会添加function。您应该只添加event listener一次。
检查tagName是否target为 an IMG,如果是,则设置src,否则不执行任何操作
//Add the event listener once the DOM loads
const getThumbnails = document.querySelector('.thumbnails');
getThumbnails.addEventListener('click', function(event) {
displaySelected(event);
});
//Check if the event target has tagName of IMG
function displaySelected(event) {
if(event.target.tagName === "IMG"){
const getMainClass = document.querySelector('img.main');
getMainClass.src = event.target.getAttribute('src');
}
}
{
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>
</main>
</body>
</html>
添加回答
举报