javascript.中。如何给多个元素添加同一个JS事件

2025-05-16 23:06:11
推荐回答(2个)
回答(1):




div{width: 150px;height: 150px;background: red;margin-bottom:5px;
}

  







window.onload = function() {
  var divs = document.getElementsByTagName("div");//获取所有的div
  for(var i = 0; i    divs[i].onmouseover = function(){
      this.style.opacity = 0.5;
    }
    divs[i].onmouseout =function(){
      this.style.opacity = 1;
    } 
  }
}


回答(2):

window.onload = function() {
var arr  =document.getElementsByTagName('div');
for (var i = 0; i < arr.length; i++) {
    var o = arr[i];
    o.onmouseover = function(){
o.style.opacity = 0.5;
    }
    o.onmouseout =function(){
o.style.opacity = 1;
    }
}
}