JavaScript - 在不使用 :hover 的情况下为多个元素设置 onmouseover

2 javascript events hover

有什么办法可以通过不使用 :hover 和不在所有元素中添加“onmouseover 和 onmouseout”来做到这一点,就像在脚本中为所有输入元素设置 onmouseover 和 onmouseout 的有效方法一样。

注意:在尝试使用 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>
Run Code Online (Sandbox Code Playgroud)

Man*_*rth 5

循环遍历所有带有input标签的元素

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

使用 jQuery:

$('input').on('mouseover',function(){/* code goes here */}).on('mouseout',function(){/* code goes here */})
Run Code Online (Sandbox Code Playgroud)