Javascript - 数组中的样式元素



我有一个图像数组,每当单击这些图像时,我想用边框设置这些图像的样式。我可以使用索引号将一张图像设置为样式,但似乎无法在单击每个图像时运行该功能。我得到一个"无法设置未定义的'边界'的属性at 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 ) ; 
}

而不是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 ) ; 
}
<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>

相关内容

  • 没有找到相关文章

最新更新