简体   繁体   English

getElementsByClassName 但只操作我想要的那个

[英]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;
  }
});

You can see a full working example here .您可以在此处查看完整的工作示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 JS .getElementsByClassName 更改文本:类名是相同的,我只想更改一个的文本 - Changing Text using JS .getElementsByClassName: Class Names are the Same, and I only want to change the text of one getElementsByClassName仅获得一项 - getElementsByClassName only getting one item 我想换一张表格时出现getElementsByClassName问题 - getElementsByClassName issue when i want to make for another form 当只有一个要选择的类时,为什么getElementsByClassName需要[0]? - Why is [0] needed for getElementsByClassName to work when there's only one class to select? 要切换的元素越多,但我只想切换我点击的元素 - More elements to be toggled, but I only want to toggle the one i clicked on 更改getElementsByClassName()[i]字段 - Change getElementsByClassName()[i] field 我想分配一个变量两次,但只想在 javascript 中使用第一个变量 - I want to assign one variable twice but only want to use first one in javascript 我只想创建一个音频播放器实例 - I want to create only one audio player instance please 如何使此代码从项目中删除类名称,然后使用getElementsByClassName并使此手风琴按我的意愿工作? - How to make this code to remove class name from items took getElementsByClassName and make this accordions work as I want them to? Discord Bot 发送多条消息,但我只希望它发送一条 - Discord Bot sends multiple messages but I only want it to send one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM