2013-02-09 43 views
0

有沒有什麼辦法可以做到這一點,不使用:懸停和不在所有元素中添加「onmouseover和onmouseout」,就像一個腳本中的有效方法巫婆設置onmouseover併爲所有輸入元素提供上傳。JavaScript - 爲多個元素設置onmouseover而不使用:hover

注意:請用JavaScript嘗試使用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

不,我建議在此之前,但你可以嘗試在將事件處理程序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小提琴(背景顏色變化)http://jsfiddle.net/Rcgx5/

0

遍歷所有與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 */}) 
+0

是的,但如果我想幹什麼來設置顏色:this.style.color =「紅色」應如何界定我的呢? – Murplyx 2013-02-09 10:55:12

+0

你可能要仔細檢查你的for循環。你應該真的使用一個傳統的for循環而不是for..in,但是即使忽略你不使用循環內的我... – nnnnnn 2013-02-09 10:55:51

+0

@nnnnnn oops,thanks :) – Manishearth 2013-02-09 10:56:38

0

你可以試試這

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.

相關問題