我得到的图像具有相同的宽度和高度,并且在单击时它们应该变大,因此我为其创建了一个带有事件监听器的函数,但现在它告诉我未定义样式,因此看不到问题。我在img标签内设置样式,也没有样式。
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />
js文件
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', () => {
if (flag == true && window.innerWidth >= 769) {
paint[i].style.maxWidth = '95vw';
paint[i].style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
paint[i].style.maxWidth = '20%';
paint[i].style.minWidth = '300px';
paint[i].style.height = 'auto';
flag = true;
}
})
}
如果我尝试使用getelementById,则一切正常,但我不希望每个图像都有一个事件监听器。
使用事件侦听器功能中的event.target
查找单击的图像。
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', (event) => {
console.log(event.target)
if (flag == true && window.innerWidth >= 769) {
event.target.style.maxWidth = '95vw';
event.target.style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
event.target.style.maxWidth = '20%';
event.target.style.minWidth = '300px';
event.target.style.height = 'auto';
flag = true;
}
})
}
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />