javascript.中。如何给多个元素添加同一个JS事件
<styletype="text/css">div{width:150px;height:150px;background:red;margin-bottom:5px;}...
<style type="text/css">
div{width: 150px;height: 150px;background: red;margin-bottom:5px;
}
</style>
<title></title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script type="text/javascript">
window.onload = function() {
var o =document.getElementsByTagName('div')[0];
o.onmouseover = function(){
o.style.opacity = 0.5;
}
o.onmouseout =function(){
o.style.opacity = 1;
}
}
</script>
</body>
</html>
比如4个div.我希望鼠标移入透明度变为0.5,鼠标移除变为1,给其中1个div加效果我知道怎么写,据说用for循环,但具体怎么写啊?(不要用伪类,) 展开
div{width: 150px;height: 150px;background: red;margin-bottom:5px;
}
</style>
<title></title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script type="text/javascript">
window.onload = function() {
var o =document.getElementsByTagName('div')[0];
o.onmouseover = function(){
o.style.opacity = 0.5;
}
o.onmouseout =function(){
o.style.opacity = 1;
}
}
</script>
</body>
</html>
比如4个div.我希望鼠标移入透明度变为0.5,鼠标移除变为1,给其中1个div加效果我知道怎么写,据说用for循环,但具体怎么写啊?(不要用伪类,) 展开
2个回答
展开全部
<html>
<head>
<style type="text/css">
div{width: 150px;height: 150px;background: red;margin-bottom:5px;
}
</style>
<title></title>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script type="text/javascript">
window.onload = function() {
var divs = document.getElementsByTagName("div");//获取所有的div
for(var i = 0; i<divs.length; i++) {//循环让每个div都有效果
divs[i].onmouseover = function(){
this.style.opacity = 0.5;
}
divs[i].onmouseout =function(){
this.style.opacity = 1;
}
}
}
</script>
</body>
</html>
展开全部
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;
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询