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

Eve*_*ner 6 javascript css

是否可以更改现有onmouseover或onmouseout事件调用的函数?对于以下示例,我有一种方法让ChangeItemAEvent将"ItemA"onmouseover函数从ChangeColor()更改为ChangeColorBack()吗?目前我需要声明一个全新的函数(),我觉得它不优雅,因为我应该能够调用现有函数时重复代码.

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";

  };
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<span id="ItemA" onmouseover="ChangeColor(this.id)">
<button id="ButtonB" onclick="ChangeItemAEvent()">
Run Code Online (Sandbox Code Playgroud)

Bry*_*eld 8

试试这个

function ChangeItemAEvent()
{
    document.getElementById("ItemA").onmouseover = function() {ChangeColorBack(this.id)};
}
Run Code Online (Sandbox Code Playgroud)