本文介绍了JavaScript - 为多个元素设置onmouseover而不使用:hover的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么方法可以通过不使用:hover,而不是在所有元素中添加onmouseover和onmouseout,就像在一个脚本中有效的方法,设置onmouseover和onmouseout的所有输入元素。

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.

注意:尝试使用JQuery

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>

推荐答案

不是我推荐这个,但是您可以尝试在body元素上放置一个事件处理程序 mouseover ,然后使用 event.target / event.srcElement 确定是否要处理该事件

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

样本JS小提琴(背景颜色更改)

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

这篇关于JavaScript - 为多个元素设置onmouseover而不使用:hover的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:36