鼠标移开按钮禁用

On mouseout button disables

我是新手所以如果我听起来很愚蠢请原谅我。

所以我试图让它在鼠标移出按钮时禁用。到目前为止,这是我尝试过的方法:(提前致谢!)

function alertonclick() {
  alert("You got me! GG. At least I tried.");
}    
function addEvent(obj, evt, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evt, fn, false);
    }
    else if (obj.attachEvent) {
        obj.attachEvent("on" + evt, fn);
    }
}      

    addEvent(document, "mouseout", function(e) {
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
          document.getElementById("button").disabled = true;
                document.getElementById("button").value = "BUTTON IS DISABLED";
                document.getElementById("button").style.background='808080';

                }
    });

HTML

<button id="button" tabindex="-1" onclick="alertonclick()" class="Rainbow buttonmove notouch button1 btn">Button</button>

试试这个:

var button = document.getElementById('button');
button.addEventListener('mouseleave', function () {
button.setAttribute('disabled', 'disabled');
});

不需要 jquery:-)

好的,首先您的整个 addEvent 功能是不需要的,除非您怀疑您可能有使用 Internet Explorer 8 的用户!自 IE 9 (1995) 以来的所有浏览器都支持 .addEventListener().

出于同样的原因,您也不需要:e = e ? e : window.event;

接下来,you shouldn't be using inline HTML event attributes 喜欢 onclick,因为它们是处理 25 多年前的事件的传统方法,直到今天仍然存在,因为人们只是看到其他人使用它们并且 copy/paste 他们不理解为什么不应该使用它们。将 JavaScript 与 HTML 分开,并使用 .addEventListener(),您在 addEvent 函数中实际使用的是 .addEventListener()

您尝试设置的颜色不正确,因为您没有在十六进制代码前添加“#”,将其标识为十六进制颜色。

最后,如果你想在鼠标返回到按钮上时能够与按钮交互,那么你真的不想禁用按钮(因为那样你就不会触发 mouseover 鼠标返回时的事件)。

真的,您的大部分代码都不需要。本质是这样的:

const btn = document.getElementById("button")

btn.addEventListener("mouseout", function(e) {
  this.textContent = "BUTTON IS DISABLED";
  this.classList.add("disabled");
});

btn.addEventListener("mouseover", function(e) {
  this.textContent = "BUTTON ENABLED";
  this.classList.remove("disabled");
});
.disabled { background-color:#808080; }
<button id="button" tabindex="-1" class="Rainbow buttonmove notouch button1 btn">Button</button>