我做了一个恶作剧计算器,当按下"="按钮时,它会从用户那里输入要显示的答案。输入采用JavaScript中的提示形式,该提示由长按"0"按钮触发。长按功能是通过在按下按钮时设置2秒的超时(使用onmousedown
(和在抬起鼠标键时清除超时(onmouseup
(来实现的。这在电脑上运行良好,但我不知道如何在手机上实现。我也尝试过onpointerdown
和onpointerup
事件。这些在电脑上也可以正常工作,但当我在手机上长按时,提示会在不久后再次显示。与此相关的HTML和JavaScript代码如下:
HTML:
<td>
<button
class="calculator-button"
onclick="insert(0)"
onmousedown="activateMagic()"
onmouseup="disableMagic()"
>
0
</button>
</td>
JavaScript:
let answer = null;
const input = document.getElementById("calcInput");
let pressTimer;
const insert = (objToInsert) => {
input.value += objToInsert;
};
const clearInput = () => {
input.value = null;
answer = null;
};
const activateMagic = () => {
pressTimer = window.setTimeout(() => {
answer = prompt("Enter the prank answer: ");
}, 2000);
return false;
};
const disableMagic = () => {
clearTimeout(pressTimer);
};
const findAnswer = () => {
if (answer == null) {
let problemAnswer = eval(input.value);
setTimeout(() => {
input.value = problemAnswer;
}, 10);
}
input.value = answer;
};
提前谢谢。
我找到了答案@DanyloHalaiko是对的。touchstart
和touchend
事件侦听器实际上工作!对于那些感兴趣或在未来看到这一点的人,这是我的最后一个代码:
HTML:
<td>
<button
class="calculator-button"
onclick="insert(0)"
onmousedown="activateMagic()"
onmouseup="disableMagic()"
id="activateBtn"
>
0
</button>
</td>
JavaScript:
let answer = null;
const input = document.getElementById("calcInput");
const activateBtn = document.getElementById("activateBtn");
let pressTimer;
const insert = (objToInsert) => {
input.value += objToInsert;
};
const clearInput = () => {
input.value = null;
answer = null;
};
const activateMagic = () => {
pressTimer = window.setTimeout(() => {
answer = prompt("Enter the prank answer: ");
}, 2000);
return false;
};
const disableMagic = () => {
clearTimeout(pressTimer);
};
activateBtn.addEventListener("touchstart", activateMagic);
activateBtn.addEventListener("touchend", disableMagic);
const findAnswer = () => {
if (answer == null) {
let problemAnswer = eval(input.value);
setTimeout(() => {
input.value = problemAnswer;
}, 10);
}
input.value = answer;
};