我有一系列图像,我想在点击它们时用边框设置这些图像的样式。我可以使用索引编号将一个图像设置为样式,但无论何时单击它都无法在每个图像上运行该功能。我得到了一个"无法设置' border'未定义的 在HTMLImageElement.picStyle"。
HTML:
<div id="pic-container">
<img class ="dogImg" src="img/dog1.jpg">
<img class ="dogImg" src="img/dog2.jpg">
<img class ="dogImg" src="img/dog3.jpg">
<img class ="dogImg" src="img/dog4.jpg">
<img class ="dogImg" src="img/dog5.jpg">
</div>
JS:
var dogPics = document.getElementsByClassName('dogImg');
function picStyle() {
dogPics.style.border = "1px solid black";
}
for (var i = 0; i < dogPics.length; i++) {
dogPics[i].addEventListener('click' , picStyle ) ;
}
答案 0 :(得分:2)
而不是dogPics.style.border
使用this.style.border
。
var dogPics = document.getElementsByClassName('dogImg');
function picStyle() {
this.style.border = "1px solid black";
}
for (var i = 0; i < dogPics.length; i++) {
dogPics[i].addEventListener('click' , picStyle ) ;
}
&#13;
<div id="pic-container">
<img class ="dogImg" src="img/dog1.jpg">
<img class ="dogImg" src="img/dog2.jpg">
<img class ="dogImg" src="img/dog3.jpg">
<img class ="dogImg" src="img/dog4.jpg">
<img class ="dogImg" src="img/dog5.jpg">
</div>
&#13;