【问题标题】:HTML onmousedown event not working on mobileHTML onmousedown 事件在移动设备上不起作用
【发布时间】:2021-05-27 23:36:26
【问题描述】:

我制作了一个恶作剧计算器,当按下“=”按钮时,它会从用户那里输入要显示的答案。输入采用 JavaScript 中的提示形式,通过长按“0”按钮触发。长按功能是通过在按下按钮时设置 2 秒的超时时间(使用onmousedown)并在鼠标键被抬起时清除超时时间(onmouseup)来实现的。这在计算机上运行良好,但我不知道如何在移动设备上实现。我也尝试过onpointerdownonpointerup 事件。这些在计算机上也可以正常工作,但是当我在手机上长按时,提示会在不久之后再次显示。与此相关的 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;
};

提前致谢。

【问题讨论】:

标签: javascript html mobile


【解决方案1】:

我找到了答案!! @DanyloHalaiko 是对的。 touchstarttouchend 事件监听器实际上工作!对于那些有兴趣或将来会看到这个的人,这是我的最终代码:

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;
};

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多