JavaScript 动态显示元素上的 touchend 未触发

JavaScript touchend on dynamically shown element doesn't fire

我注意到触摸事件中有一个奇怪的行为。情况是这样的:我有一个#pointercapturediv,默认是隐藏的。 touchstart 处理程序附加到主体,这导致 pointercapture 显示(覆盖主体)。 pointercapture 附加了 touchend 事件,隐藏了它。问题是在 touchstart pointercapture 上出现,在 touchend 上它不隐藏。你必须触摸屏幕并再次释放它才能消失。 这是 fiddle。我还附加了鼠标事件,它们按预期工作(pointercapture 隐藏在第一个 mouseup 上)。 https://jsfiddle.net/3p8eyug5/

HTML

<body>
<div id="pointercapture"></div>
</body>

CSS

body {
  width:500px;
  height:500px;
  background:green;
}
#pointercapture {
  display:none;
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:orange;
}

JavaScript

  var $=jQuery;
$('body').on('touchstart mousedown', function(e) {
    $('#pointercapture').show();
    e.preventDefault();
});

$('#pointercapture').on('touchend mouseup', function(e) {
    $(this).hide();
    e.preventDefault();
});

有人可以解释这种行为吗?我也很好奇它是如何与指针事件和触摸一起工作的,我现在没有办法检查它。

这是预期的行为。一旦主体捕获到 touchstart 事件,它就会通过 touchend 保持整个触摸动作(触摸事件出现时不会传输到#pointercapture)。您只需将 touchend 事件而不是 #pointercapture 放在 body 上,它应该会像您描述的那样工作。

$('body').on('touchstart mousedown', function(e) {
    $('#pointercapture').show();
    e.preventDefault();
});

$('body').on('touchend mouseup', function(e) {
    $('#pointercapture').hide(); // also change this to #pointercapture
    e.preventDefault();
});

https://jsfiddle.net/3p8eyug5/1/