JavaScript - Set onmouseover for multiple elements without using :hover

谁说我不能喝 提交于 2020-01-06 07:46:27

问题


Is there any way I can do this by not using :hover and by not adding "onmouseover and onmouseout" in all elements, like an effective way in a script witch sets onmouseover and onmouseout for all input elements.

NOTE: Please try with JavaScript before trying with JQuery


<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>


回答1:


Loop through all the elements with the input tag

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

With jQuery:

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



回答2:


You may try this

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';
    };
};

DEMO.




回答3:


Not that I recommend this, but you could try putting an event handler for mouseover on the body element and then use event.target / event.srcElement to determine whether you want to handle the event or not

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);

Sample JS Fiddle (with background color change) http://jsfiddle.net/Rcgx5/



来源:https://stackoverflow.com/questions/14787248/javascript-set-onmouseover-for-multiple-elements-without-using-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!