gpt4 book ai didi

Javascript if 检测保持在 for 循环中运行

转载 作者:行者123 更新时间:2023-11-28 04:46:18 25 4
gpt4 key购买 nike

我一直在弄清楚如何检测它是否是对 HTML 按钮的长按。目前它只是逐像素移动 snap

有没有办法检测按钮上的 hold 并在 forloop 中运行它?我已经尝试过 onlongclick,但没有成功。

function load() {
var context = document.getElementById('main').getContext("2d");
var left = document.getElementById('left');
var down = document.getElementById('down');
var right = document.getElementById('right');
var imgLoaded = false;
var posX = 250;
var posY = 0;
var snap = 10;


var img = new Image();
img.onload = function() {
imgLoaded = true;
context.drawImage(img, posX, posY);
};
img.src = "start.png";

// left button click
left.onclick = function() {
if (!imgLoaded) return;
posX = posX - snap;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.drawImage(img, posX, posY);
};

// down button click
down.onclick = function() {
if (!imgLoaded) return;
posY = posY + snap;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.drawImage(img, posX, posY);
};

// right button click
right.onclick = function() {
if (!imgLoaded) return;
posX = posX + snap;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.drawImage(img, posX, posY);
};

}

HTML 按钮:-

<aside class="socialNetworkNavBar">
<div id="left" style="margin-right: 50px;" class="socialNetworkNav">
<!-- Add a Anchor tag with nested img tag here -->
<input type="image" src="images/left.png">

</div>
<div id="down" style="margin-right: 50px;" class="socialNetworkNav">
<!-- Add a Anchor tag with nested img tag here -->
<input type="image" src="images/down.png"> </div>
<div id="right" style="margin-right: 50px;" class="socialNetworkNav">
<!-- Add a Anchor tag with nested img tag here -->
<input type="image" src="images/UXwr4.png">
</div>

</aside>

最佳答案

click 是一个事件,其中鼠标按下释放了按钮。如果您想检测这是否是一次点击,您可以添加一个mousedown 监听器,并存储按下按钮的时间:

left.onmousedown = function() {
left.dataset.start = new Date().getTime();
};

left.onclick = function() {
var diff = new Date() - parseInt(left.dataset.start);
if(diff / 1000 > 3) {
// Mouse-down was more than three seconds ago, this was a long click
}
};

如果你想在按钮仍被按下时连续执行一个 Action ,你可以将该 Action 作为一个间隔运行,当按钮被释放时中断:

left.onmousedown = function() {
left.dataset.interval = window.setInterval(function() {
// perform action
}, 250);
};

left.onmouseup = function() {
window.clearInterval(parseInt(left.dataset.interval));
};

left.onmouseout = function() {
window.clearInterval(parseInt(left.dataset.interval));
};

关于Javascript if 检测保持在 for 循环中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com