【问题标题】:touchmove events stop after replacing innerHTMLtouchmove 事件在替换 innerHTML 后停止
【发布时间】:2017-09-20 17:52:13
【问题描述】:

我有一个网页跟踪 touchmove 事件,允许用户在屏幕上拖动元素 - 工作正常。

在用户移动时动态替换移动元素中的 html - 替换 html 效果很好。

问题是如果用户通过触摸内部 html(被替换)进行拖动,那么一旦内部 html 被替换(直到下一次 touchstart),拖动(touchmove 事件)就会停止。 p>

事件侦听器位于外部容器上,而不是被替换的 html,所以我认为它应该继续捕获事件。

mousemove 事件也不会出现此问题。

我做了一个 jsfiddle 演示。使用鼠标应该可以正常工作并且不会发生任何问题(mousemove 事件)。当您使用触摸设备(或使用 Chrome 的触摸模拟:更多工具 > 传感器 > 触摸 > 强制启用)时会出现此问题。

https://jsfiddle.net/dmdjvd7e/1/

相同但使用 jquery:https://jsfiddle.net/a2fwkr4e/6/

在演示中,您可以拖动屏幕周围的红色圆圈。 圆圈内的黄色框每秒更换一次。 如果您触摸红色(不是黄色),那么一切都会正常工作。 如果您触摸黄色,那么一切都会正常工作,直到黄色框被替换(每秒),之后您将不会移动元素,直到您再次触摸开始。

这是预期的浏览器行为吗?为什么mousemove不同? 有没有办法解决这个问题,同时仍然允许我替换 html?

如果我不替换内部 html,而只是修改它或只是替换文本而不是 html 元素,那么就没有问题。但是,我希望能够替换 html(根据现有的应用程序要求)。

...

为了完整性而包含的代码(与 jsfiddle 相同):

css/html:

<style>
.container {
  user-select: none;
  background-color: gray;
  position: absolute;
  top:0;
  left:0;
  bottom:0;
  right:0;
}

.dot {
  border-radius: 100%;
  background-color: red;
  padding: 2em;
  margin: -4em 0 0 -4em;
  position: absolute;
  top: 3em;
  left: 3em;
  color: blue;
}
.dot div {
  font-weight: bold;
  color: black;
  background-color: yellow;
  padding: 2em;
}
</style>
<div class='container'>
  <div class='dot'><div class='num'>0</div></div>
</div>

js:

var eContainer = document.querySelector('.container'),
eDot = document.querySelector('.dot'),
dragActive = false,
val = 0;

var hInterval = setInterval(function() {
    ++val;
    eDot.innerHTML = '<div class="num">' + val + '</div>';
}, 1000);

eContainer.addEventListener('touchstart', dragStart);
eContainer.addEventListener('touchend', dragEnd);
eContainer.addEventListener('touchmove', dragMove);

eContainer.addEventListener('mousedown', dragStart);
eContainer.addEventListener('click', dragEnd);
eContainer.addEventListener('mousemove', dragMove);

function dragStart(e) {
    dragActive = true;
}

function dragMove(e) {
    if (!dragActive) return;

  var posX = e.clientX || (e.touches && e.touches.length ? e.touches[0].pageX : 0),
        posY = e.clientY || (e.touches && e.touches.length ? e.touches[0].pageY : 0);

  eDot.style.left = posX + 'px';
  eDot.style.top = posY + 'px';
}

function dragEnd(e) {
    dragActive = false;
}

在 Chrome 62 和 Firefox 56(均在 Windows 10 上)和 Chrome 60 (Android N) 以及 Safari/webkit 602.1 (iPhone 6) 上进行了测试。

【问题讨论】:

    标签: javascript html events touch touchmove


    【解决方案1】:

    嗯.. 我想我应该阅读规范:

    “此事件的目标必须与触摸点第一次放置在表面上时开始的元素相同,即使触摸点已经移出目标元素的交互区域。”

    https://www.w3.org/TR/touch-events/#the-touchmove-event

    此外,在所有输入之后,我发现已经提出了相同的问题并且有几个答案:Touch Move event don't fire after Touch Start target is removed

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多