2010-10-15 109 views
6

是否可以更改由現有onmouseover或onmouseout事件調用的函數?對於下面的例子有沒有辦法讓我ChangeItemAEvent更改「ItemA」onmouseover函數從ChangeColor()更改爲ChangeColorBack()?目前,我需要聲明一個全新的函數(),我覺得它不夠優雅,因爲我應該能夠調用現有函數時重複代碼。動態更改onmouseover或onmouseout以調用其他函數

的javascript:

function ChangeColor(elementid) 
{ 
    document.getElementById(elementid).style.background = "Orange"; 
    document.getElementById(elementid).style.color = "Black"; 
} 

function ChangeColorBack(elementid) 
{ 
    document.getElementById(elementid).style.background = "Black"; 
    document.getElementById(elementid).style.color = "White"; 
} 

function ChangeItemAEvent() 
{ 
    document.getElementById("ItemA").onmouseover = function() { 

    document.getElementById("ItemA").style.background = "Black"; 
    document.getElementById("ItemA").style.color = "White"; 

    }; 
} 

HTML:

<span id="ItemA" onmouseover="ChangeColor(this.id)"> 
<button id="ButtonB" onclick="ChangeItemAEvent()"> 

回答

8

試試這個

function ChangeItemAEvent() 
{ 
    document.getElementById("ItemA").onmouseover = function() {ChangeColorBack(this.id)}; 
} 
2

是否有可能改變由現有的onmouseover或onmouseout事件調用的函數?

是的,通過寫入DOM element.onmouseover屬性,具有函數值。這可以是函數名稱或內聯函數表達式。

如果您寫信給事件處理程序的屬性(或添加事件監聽器),你可以採取的this優勢指向的元素,並避免將周圍的ID,這使得它更容易做你的腳本:

<span id="ItemA"> 
<button type="button" id="ButtonB"> 

<script type="text/javascript"> 
    function ChangeColor() { 
     this.style.background= 'orange'; 
     this.style.color= 'black'; 
    } 

    function ChangeColorBack(elementid) { 
     this.style.background= 'black'; 
     this.style.color= 'white'; 
    } 

    document.getElementById('ItemA').onmouseover= ChangeColor; 
    document.getElementById('ButtonB').onclick= function() { 
     document.getElementById('ItemA').onmouseover= ChangeColorBack; 
    }; 
</script> 

然而,對於這種懸停和選擇工作,通常最好使用狀態變量或CSS,而不是重新分配事件處理程序。例如像:

#ItemA:hover { background: orange; color: black; } 
#ItemA.selected:hover { background: black; color: white; } 

document.getElementById('ButtonB').onclick= function() { 
    var a= document.getElementById('ItemA'); 
    a.className= a.className==='selected'? '' : 'selected'; 
}; 

:hover上跨度不工作在IE6,因此,如果您需要的是瀏覽器的懸停高亮,你就必須有onmouseover/mouseout代碼中添加或刪除.hover className)。

相關問題