我希望按钮在点击时更改颜色(mousedown上的深色阴影和鼠标上的原始颜色)并且仅在第二次点击时才有效。这是为什么?我该如何解决这个问题?
按钮ID为1到10(button1,button2 ...)
document.getElementById('main').addEventListener('click', function(e) {
var buttonNum = e.target.id.substring(6);
if (e.target.id.substring(0,6) === "button") {
e.target.addEventListener('mousedown', function() {mouseDown(buttonNum)}, false);
e.target.addEventListener('mouseup', function() {mouseUp(buttonNum)}, false);
// trying another way:
// mouseEventHandler(buttonNum);
result.innerHTML = e.target.innerHTML + " was clicked";
}
}, false);
var mouseupColors = ["#CE3737",
"#48935C",
"#FFD454",
"#26567C",
"#FF6528",
"#92898A",
"#AF9FA5",
"#9EA9AA",
"#989788",
"#7C7372"]
var mousedownColors = ["#B52D2D",
"#397A4A",
"#E5BF4B",
"#183F63",
"#E55B24",
"#777071",
"#96888D",
"#879091",
"#7F7E71",
"#635C5B"]
function mouseDown(buttonNum) {
var buttonId = "button" + buttonNum;
document.getElementById(buttonId).style.backgroundColor = mousedownColors[buttonNum - 1];
}
function mouseUp(buttonNum) {
var buttonId = "button" + buttonNum;
document.getElementById(buttonId).style.backgroundColor = mouseupColors[buttonNum - 1];
}
我也尝试过创建一个处理mousedown和mouseup的函数。它有相同的结果。
var mouseEventHandler = function(buttonNum) {
var buttonId = "button" + buttonNum;
document.getElementById(buttonId).onmousedown = function() {
this.style.backgroundColor = mousedownColors[buttonNum - 1];
};
document.getElementById(buttonId).onmouseup = function() {
this.style.backgroundColor = mouseupColors[buttonNum - 1];
};
};
答案 0 :(得分:1)
mouseup
和mousedown
个事件在click
事件处理程序中注册。因此,第一次单击该按钮时,这两个事件尚未设置。
您需要在点击处理功能之外添加这些事件。例如。 https://jsfiddle.net/Lj8kyr7e/6/