我正在学习JavaScript,并且在MDN中进行the gallery示例时遇到了一个奇怪的情况。我决定在此示例中添加一个简单的函数,但是没有用。我的目标是为“ .displayed-img” img添加一个功能。
我知道问题出在“覆盖” div。当我在HTML中注释该行时,就可以运行我的函数。但是我不知道当我遇到这样的情况并且需要访问位于另一个对象下面的对象时,哪种方法是最好的?谢谢。
这是我的代码:
var displayedImage = document.querySelector('.displayed-img');
var thumbBar = document.querySelector('.thumb-bar');
var btn = document.querySelector('button');
var overlay = document.querySelector('.overlay');
var imgUrl, currentImgUrl;
/* Looping through images */
for (var i = 0; i < 5; i++) {
imgUrl = 'https://via.placeholder.com/640x48'+(i+1)+'.jpg';
var newImage = document.createElement('img');
newImage.setAttribute('src', imgUrl);
thumbBar.appendChild(newImage);
newImage.addEventListener ('click', function(e){
displayedImage.setAttribute('src', e.target.getAttribute('src'));
} );
}
displayedImage.addEventListener('click', sayHi);
function sayHi(){
console.log('hi');
}
btn.onclick = function() {
if (btn.getAttribute('class')==='dark') {
overlay.style.backgroundColor = 'rgba(0,0,0,0.5)';
btn.textContent = 'Light';
btn.setAttribute('class', 'light');
} else {
overlay.style.backgroundColor = 'rgba(0,0,0,0)';
btn.textContent = 'Darken';
btn.setAttribute('class', 'dark');
}
}
body {
width: 640px;
margin: 0 auto;
}
.full-img {
position: relative;
display: block;
width: 640px;
height: 480px;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 640px;
height: 480px;
background-color: rgba(0, 0, 0, 0);
}
button {
border: 0;
background: rgba(150, 150, 150, 0.6);
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
cursor: pointer;
top: 2px;
left: 2px;
}
.thumb-bar img {
display: block;
width: 20%;
float: left;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image gallery</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Image gallery example</h1>
<div class="full-img">
<img class="displayed-img" src="https://via.placeholder.com/640x480">
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>
<div class="thumb-bar">
</div>
<script src="main.js"></script>
</body>
</html>