[英]getElementsByClassName but manipulate only the one that i want
i have multiple div with same classname but i want to change only one of their opacity, the one that i interact with a mouse or touch.我有多个具有相同类名的 div,但我只想更改其中一个不透明度,即我与鼠标或触摸交互的不透明度。 How can i do it?我该怎么做? The below code changing all of theirs properties, apparently.显然,下面的代码改变了他们所有的属性。 Full.js code is here if anyone would like to take a look at: https://jsfiddle.net/b7y6mfv4/如果有人想看一下,这里有 Full.js 代码: https://jsfiddle.net/b7y6mfv4/
var target1 = document.getElementsByClassName('beforeLabel');
var target2 = document.getElementsByClassName('afterLabel');
for (var i=0; i<target1.length; i++) {
target1[i].style.opacity = beforeAfter;
target2[i].style.opacity = beforeAfter2;
}
Based on your fiddle, change document.getElementsByClassName
to evt.target.getElementsByClassName
and get rid of the loop.根据您的小提琴,将document.getElementsByClassName
更改为evt.target.getElementsByClassName
并摆脱循环。
Target lets you reference only the element that is the target of the event. Target 允许您仅引用作为事件目标的元素。
Your JS is looping through all elements with either of those two class names and applying opacity.您的 JS 正在遍历所有具有这两个 class 名称之一的元素并应用不透明度。 What you can do is make use of the mouse events target property, which will give you the specific element which has been interacted with, and apply the opacity to that.您可以做的是利用鼠标事件目标属性,这将为您提供与之交互的特定元素,并将不透明度应用于该元素。
document.addEventListener('mouseover', (event) => {
if (event.target.className.includes("beforeLabel")) {
event.target.style.opacity = 0.5;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.