3

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

4

3 に答える 3

5

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 */})
于 2013-02-09T10:52:24.803 に答える
3

mouseoverこれをお勧めするわけではありませんが、 body 要素にイベント ハンドラーを配置してから、 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/

于 2013-02-09T10:50:33.870 に答える
1

あなたはこれを試すことができます

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

デモ。

于 2013-02-09T10:55:00.647 に答える