JavaScript - Set onmouseover for multiple elements

2019-09-09 08:00发布

问题:

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:

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/



回答3:

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.