基于问题press and hold button javascript和小提琴http://jsfiddle.net/0bs3omjj/1/我想将代码更改为其他方案。我想检查button1是否在onmousedown - hold - onmouseup,如果是这样......查询选择器应该更改为下一个按钮
我试过这个
<div id="myDIV">
<button class="myButton">button 1</button>
<button class="myButton">button 2</button>
<button class="myButton">button 3</button>
<button class="myButton">button 4</button>
</div>
和JavaScript
var mouse_is_down = false;
var current_i = 0;
var buttoncounter = 1;
var button = "";
var buttoncount = 0;
function changebutton() {
var x = document.getElementById("myDIV").querySelectorAll(".myButton");
x[buttoncount].style.backgroundColor = "red";
button = x[buttoncount];
buttoncount++;
}
changebutton();
button.onmousedown = function(){
mouse_is_down = true;
console.log("mousedown" + buttoncounter);
setTimeout(
(function(index){
return function(){
if(mouse_is_down && current_i === index){
//do thing when hold
console.log("hold" + buttoncounter);
console.log(button);
}
};
})(++current_i), 500); // time you want to hold before fire action
};
button.onmouseup = function(){
mouse_is_down = false;
current_i++;
console.log("onmouseup" + buttoncounter);
console.log("change selector");
buttoncounter++;
changebutton();
console.log(button);
};
但查询选择器仅响应第一个按钮(单击并保持) - 但javascript会更改其他按钮的颜色值。有什么问题?
答案 0 :(得分:1)
首先,不要多次使用相同的ID。
其次,您正走在正确的道路上,只需将onmouseup
和其他来电置于您的changebutton()
功能中:
您的HTML:
<div id="myDIV">
<button class="myButton">button 1</button>
<button class="myButton">button 2</button>
<button class="myButton">button 3</button>
<button class="myButton">button 4</button>
</div>
您的Javascript:
var mouse_is_down = false;
var current_i = 0;
var buttoncounter = 1;
var button = "";
var buttoncount = 0;
function changebutton() {
var x = document.getElementById("myDIV").querySelectorAll(".myButton");
x[buttoncount].style.backgroundColor = "red";
button = x[buttoncount];
button.onmousedown = function(){
mouse_is_down = true;
setTimeout(
(function(index){
return function(){
if(mouse_is_down && current_i === index){
//do thing when hold
console.log("hold" + buttoncounter);
console.log(button);
}
};
})(++current_i), 500); // time you want to hold before fire action
};
button.onmouseup = function(){
mouse_is_down = false;
current_i++;
buttoncounter++;
changebutton();
};
buttoncount++;
}
changebutton();