我正在尝试制作HTML5游戏,只要玩家按下LMB,子弹就会继续产生,一旦LMB被释放,拍摄就会停止。这是我的功能:
document.onclick = function(mouse){
console.log("Shoot");
}
只有在LMB发布后,该消息才会显示在控制台日志中。 我确实查看了stackoverflow并发现了这个: Qt mouseMoveEvent only when left mouse button is pressed 但我没能将它整合到我的画布中...它不会做任何事情。 谢谢你的时间。
答案 0 :(得分:1)
如果您需要在按下鼠标时执行代码,则应使用 mousedown 而不是 onclick 。
检查w3c上的鼠标事件示例。 http://www.w3schools.com/js/js_events_examples.asp
答案 1 :(得分:1)
"的onclick"在鼠标单击时调用该函数。您需要一个更具体的事件监听器。
如果您的用例准确无误,那么您所期待的是" onmousedown"。
有关详细信息,请参阅此链接:http://www.w3schools.com/jsref/event_onmousedown.asp
只需更换" onclick"与" onmousedown"。
希望有所帮助!!
答案 2 :(得分:0)
当 发布 鼠标按钮而不是按住鼠标按钮时,会调用onclick
方法。您需要的是mousedown
方法。
此外,您需要稍微改写一下您的问题。据我了解,
您希望某些事情发生 鼠标键 下来。
为此,您需要在某个合理的时间间隔内调用mousedown
活动。
var mousedownID = -1; //Global ID of mouse down interval
function mousedown(event) {
if(mousedownID==-1) //Prevent multimple loops!
mousedownID = setInterval(whilemousedown, 100 /*execute every 100ms*/);
}
function mouseup(event) {
if(mousedownID!=-1) { //Only stop if exists
clearInterval(mousedownID);
mousedownID=-1;
}
}
function whilemousedown() {
/*put your code here*/
/* i.e, whatever you what to keep on happening while the button is down*/
}
//Assign events
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
//Also clear the interval when user leaves the window with mouse
document.addEventListener("mouseout", mouseup);