我正在尝试通过使用javascript单击图像来更改图像的不透明度,但不断出现以下错误(我也是Java语言的新手):
未捕获的TypeError:无法读取的属性'getElementsByTagName' 在HTMLDivElement.thumbnails。(匿名函数).onclick
处为null
let thumbnails = document.querySelectorAll(".thumbnail");
for (let i = 0; i < thumbnails.length; i++) {
thumbnails[i].onclick = function () {
document.getElementById(thumbnails[i]).getElementsByTagName('img').style.opacity = 1;
}
}
答案 0 :(得分:1)
您已经引用了缩略图元素,因此不需要通过id来获取它。您想要这样的东西:
let thumbnails = document.querySelectorAll(".thumbnail");
for (let i = 0; i < thumbnails.length; i++) {
thumbnails[i].onclick = function() {
thumbnails[i].querySelector('img').style.opacity = 0.5;
}
}
<div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div>
<div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div><div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div><div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div><div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div><div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div><div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div><div class="thumbnail"><img src="https://via.placeholder.com/350x150"/></div>
答案 1 :(得分:0)
Document.querySelectorAll() 返回类似数组的NodeList
您不能使用getElementsByTagName,您可能想迭代该数组并在每个元素中找到子代。为此,您需要再次使用查询选择器。
答案 2 :(得分:0)
thumbnails[i]
已经是一个元素,不需要getElementById
,
因此,考虑到您已经拥有父元素,请使用firstElementChild
let thumbnails = document.querySelectorAll(".thumbnail");
for (let i = 0; i < thumbnails.length; i++) {
thumbnails[i].onclick = function() {
thumbnails[i].firstElementChild.style.opacity = 1;
}
}
<div class="thumbnail"><img src="https://i.imgur.com/GszSyNI.jpg" style="width:60px; opacity: .4"></div>
<div class="thumbnail"><img src="https://i.imgur.com/GszSyNI.jpg" style="width:60px; opacity: .2"></div>
<div class="thumbnail"><img src="https://i.imgur.com/GszSyNI.jpg" style="width:60px; opacity: .1"></div>
答案 3 :(得分:0)
如果.thumbnail
是图像的父元素的类:
let thumbnails = document.querySelectorAll(".thumbnail img");
for (let i = 0; i < thumbnails.length; i++) {
thumbnails[i].onclick = function() {
this.style.opacity = .5;
}
}
.thumbnail {
width: 50px;
height: 50px;
padding: 5px;
}
<div class="thumbnail">
<img src="https://via.placeholder.com/50x50" />
</div>
<div class="thumbnail">
<img src="https://via.placeholder.com/50x50" />
</div>
答案 4 :(得分:0)
您正在将变量thumbnails[i]
传递给方法document.getElementByID
其次,getElementsByTagName
返回元素的集合。如果您的.thumbnail中只有1个img,则使用querySelector('img')
(如果更多),则遍历整个数组。
这是仅考虑img
.thumbnail
的示例
let thumbnails = document.querySelectorAll(".thumbnail");
for (let i = 0; i < thumbnails.length; i++) {
thumbnails[i].onclick = function () {
thumbnail[i].querySelector('img').style.opacity = 1;
}
}