动态更改onmouseover或onmouseout以调用不同函数

8

有没有可能修改现有的onmouseover或onmouseout事件所调用的函数?例如,对于下面的例子,是否有办法让ChangeItemAEvent将“ItemA”的onmouseover函数从ChangeColor()更改为ChangeColorBack()?目前,我需要声明一个完全新的function(),这并不优雅,因为我在重复代码,而我应该能够调用现有的函数。

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()">
2个回答

13

试试这个

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

(在IE6中,对于一个span元素的:hover伪类不起作用。因此,如果您需要让该浏览器实现悬停高亮效果,则需要使用onmouseover/mouseout代码来添加或删除.hover类名。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接