JavaScript-不使用:hover为多个元素设置onmouseover

JavaScript - Set onmouseover for multiple elements without using :hover

本文关键字:元素 设置 onmouseover hover JavaScript-      更新时间:2023-09-26

有没有什么方法可以做到这一点,不使用:悬停,也不在所有元素中添加"onmouseover和onmouseout",就像脚本中为所有输入元素设置onmousever和onmouse out的有效方法一样。

注意:在尝试JQuery 之前,请先尝试使用JavaScript


<head>
    <title>123</title>
    <style>
    .button {
    color: red;
    }
    .button:hover {
    color: blue;
    }
    </style>
</head>
<body>
    <div>
        <input class="button" type="button" value="1">
        <input class="button" type="button" value="2">
        <input class="button" type="button" value="3">
    </div>
</body>

使用input标签循环所有元素

a=document.getElementsByTagName('input')
for (i in a){
   a[i].onmouseover=function(){/* code goes here */}
   a[i].onmouseout=function(){/* code goes here */}
}

使用jQuery:

$('input').on('mouseover',function(){/* code goes here */}).on('mouseout',function(){/* code goes here */})

我不建议这样做,但您可以尝试在body元素上放置mouseover的事件处理程序,然后使用event.target/event.srcElement来确定是否要处理事件

document.body.addEventListener("mouseover",function(e) {
    e = e || window.event;
    var targetElem = e.target || e.srcElement;
    // you can use a switch on the nodeName and handle event
    switch(targetElem.nodeName) {
        case 'INPUT':
            // do something
        break;
    }
},false);

JS Fiddle示例(背景颜色发生变化)http://jsfiddle.net/Rcgx5/

你可以试试这个

window.onload=function(){
    document.onmouseover=function(e){
        var e = e || window.event, el = e.target || el.srcElement;
        if(el.type == 'button') el.style.color='red';
    };
    document.onmouseout=function(e){
        var e = e || window.event, el = e.target || el.srcElement;
        if(el.type == 'button') el.style.color='black';
    };
};

演示