javascript鼠标点击错误

javascript on mouse click error

本文关键字:错误 鼠标 javascript      更新时间:2023-09-26

我似乎无法让mousedown和mouseup工作。我需要一个对象来改变鼠标向下和鼠标向上的颜色变回原来的。但由于某种原因

onload = init;
function init() {
    document.getElementsByClassName("buttons")[0].mousedown = function () {
        blue();
    };
    document.getElementsByClassName("buttons")[0].mouseup = function () {
        green();
    };
}
function green() {
    document.getElementsByClassName("buttons")[0].style.backgroundColor = "#360"
}
function blue() {
    document.getElementsByClassName("buttons")[0].style.backgroundColor = "blue"
};

为什么需要javascript来执行此操作?为什么不在CSS中使用":active"呢?

button{background-color: green}
button:active{background-color: blue}

事件名称包括on前缀:它是onmousedownonmouseup:

function init() {
    document.getElementsByClassName("buttons")[0].onmousedown = blue;
    document.getElementsByClassName("buttons")[0].onmouseup = green;
}