javascript – addEventListener来更改一个类中所选id的CSS样式

我有很多img具有相同的类和正确的id.

<img class="ico" id="n1"></img>
<img class="ico" id="n2"></img>

我希望在鼠标悬停/鼠标移动时更改所选img的不透明度.
我尝试使用指定的ID并工作:

var x = document.getElementById("n1");
x.addEventListener("mouseover", function(){ 
    mOverImg(document.getElementById("n1")); });
x.addEventListener("mouseout", function(){ mOutImg(document.getElementById("n1")); });

function mOverImg(img) {
    img.style.opacity="0";
}

function mOutImg(img) {
    img.style.opacity="1";
}

现在我如何处理所有图像?我尝试过这样的事情但结果不好.

var icone = document.getElementsByClassName("ico");
for (var i=0; i<icone.length; i++){           
    icone[i].addEventListener("mouseover", mOverImg);
    icone[i].addEventListener("mouseout", mOutImg);
}
function mOverImg(e) {                
    e.target.querySelector("img").style.opacity="1";                
}

我也尝试过:

var icone = document.getElementsByClassName("icone");
for (var i=0; i<icone.length; i++){
    var x = document.getElementById(icone[i].getAttribute('id') );
    x.addEventListener("mouseover", function(){ mOverImg(x)} );
    x.addEventListener("mouseout", function(){ mOoutImg(x)} );
}

还有这个….. :

 $(".icone").children().on("mouseover", function(){
     $(this).css("opacity", "1");
 });

我不明白我该怎么做.

现在我也有很多:

<div class="container">
    <p>Paragraph</p>
    <div>Empty</div>
</div>

我希望将样式更改为p,并在容器div上鼠标悬停/鼠标移动时清空div.我试过这个并且工作但是我不想重复所有:

<div class="container" onm ouseover="mOver(b1, p1)" onm ouseout="mOut(b1, p1)">
    <p id="p1">Paragraph</p>
    <div id="b1"></div>
</div>

function mOver(obj, p) {
    obj.style.borderColor="white";
    p.style.color="white";
}

function mOut(obj, p) {
   obj.style.borderColor="green";
   p.style.color="#399AF6";
}

解决方法:

请尝试以下方法:

var x = document.querySelectorAll(".ico");
x.forEach(function(img){
  img.addEventListener("mouseover", function(){ mOverImg(img) });
  img.addEventListener("mouseout", function(){ mOutImg(img) });
});

function mOverImg(img) {
  img.style.opacity="0";
}

function mOutImg(img) {
  img.style.opacity="1";
}
<img class="ico" id="n1" alt="one"/>
<img class="ico" id="n2" alt="two"/>

至于你的第二个查询:

function mOver(thatElement) {
  thatElement.querySelector('#p1').style.color="white";
  thatElement.querySelector('#b1').style.color="white";
}

function mOut(thatElement) {
  thatElement.querySelector('#p1').style.color="green";
  thatElement.querySelector('#b1').style.color="green";
}
<div class="container" onm ouseover="mOver(this)" onm ouseout="mOut(this)">
    <p id="p1">Paragraph</p>
    <div id="b1">Empty</div>
</div>
上一篇:javascript – 删除或销毁事件侦听器


下一篇:javascript – “DomContentLoaded”在我的浏览器中不起作用?