等同于mousedown的JS touch事件

时间:2018-10-28 10:12:30

标签: javascript html

在单击/触摸时尝试将数字增加一个,在按住时尝试增加一个。这是用鼠标工作的(似乎有点问题)。但是如何通过“触摸”事件使它与触摸设备配合使用?

我想像下面那样做,因为我有许多按钮可以完成相同的工作。也请使用纯JS。

window.addEventListener("load", function() {
  var count = 0;
  var iv = null;

  ["btn-1", "btn-2"].forEach(function(object) {
    ["click", "mousedown", "mouseup", "mouseleave", "touchstart"].forEach(function(event) {
      document.getElementById(object).addEventListener(event, function() {
        if (event == "mousedown" | "click" | "touchstart") {
          iv = setInterval(function() {
            if (object == "btn-1") {
              count++;
            } else {
              count--;
            }
            document.getElementById("count").innerHTML = count;
          }, 100);

        } else {
          clearInterval(iv);
        }
      });
    });
  });
});
#btn-1 {
  width: 6em;
  height: 6em;
}

#btn-2 {
  position: relative;
  top: -0.6em;
  width: 6em;
  height: 6em;
}

#count {
  position: relative;
  font-size: 4em;
  top: 0.3em;
  left: 1em;
}
<head>
</head>

<body>
  <button id="btn-1">button up</button>
  <button id="btn-2">button down</button>
  <label id=count>0</label>
</body>

1 个答案:

答案 0 :(得分:2)

如果您将条件更改为if (event == "mousedown" || event == "click" || event == "touchstart"),它将起作用。至少,它对我有用。 |bitwise operator,当像您一样使用时,一切都会变成不确定的行为。

编辑:我认为mousedown事件起作用是因为首先评估条件event == "mousedown",结果变为true。最后,我们有true | "click" | "touchstart",它也返回true。

但是,对于单击和触摸启动,第一次比较返回false,而false | "click" | "touchstart"返回false,因此该条件将永远不会执行。

希望这对您有所帮助。 干杯!

console.log("mousedown" | "click" | "touchstart")

event = "mousedown";
console.log(event == "mousedown" | "click" | "touchstart")
console.log(true | "click" | "touchstart")

event = "click";
console.log(event == "mousedown" | "click" | "touchstart")

event = "touchstart";
console.log(event == "mousedown" | "click" | "touchstart")