要检测按住按钮的时间,可以通过以下几种方法实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button Hold Time</title>
</head>
<body>
<button id="myButton">Press and Hold Me</button>
<p id="timeDisplay">0 ms</p>
<script>
const button = document.getElementById('myButton');
const timeDisplay = document.getElementById('timeDisplay');
let startTime;
button.addEventListener('mousedown', () => {
startTime = new Date().getTime();
});
button.addEventListener('mouseup', () => {
const endTime = new Date().getTime();
const holdTime = endTime - startTime;
timeDisplay.textContent = `${holdTime} ms`;
});
</script>
</body>
</html>
如果你更喜欢使用jQuery,代码会更加简洁:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Button Hold Time</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="myButton">Press and Hold Me</button>
<p id="timeDisplay">0 ms</p>
<script>
$(document).ready(function() {
let startTime;
$('#myButton').on('mousedown', function() {
startTime = new Date().getTime();
});
$('#myButton').on('mouseup', function() {
const endTime = new Date().getTime();
const holdTime = endTime - startTime;
$('#timeDisplay').text(`${holdTime} ms`);
});
});
</script>
</body>
</html>
通过以上方法,你可以有效地检测用户按住按钮的时间,并根据需要进行相应的处理。
Elastic 实战工作坊
Elastic 实战工作坊
腾讯技术创作特训营第二季第4期
云+社区沙龙online [技术应变力]
云+社区沙龙online [技术应变力]
腾讯技术创作特训营第二季第3期
腾讯云GAME-TECH游戏开发者技术沙龙
腾讯云GAME-TECH游戏开发者技术沙龙
腾讯云GAME-TECH游戏开发者技术沙龙
腾讯云GAME-TECH游戏开发者技术沙龙
腾讯云GAME-TECH沙龙
领取专属 10元无门槛券
手把手带您无忧上云