我正在尝试使用下一个模式实现类似拖动的功能:
-
订阅marker指针向下事件 .
-
当Down事件触发时,订阅Window Pointer Move和Up事件并删除标记 .
-
在移动时执行一些操作 .
-
当Up事件触发取消订阅Move和Up时 .
这适用于鼠标事件,但在删除Touch Start目标元素后不会触发 . 我试图使用Pointer Events Polyfill但它也不起作用 .
我正在使用Chrome Dev Tools来模拟触摸事件 . 看样品:
initTestBlock('mouse', {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup'
});
initTestBlock('touch', {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
});
initTestBlock('touch-no-remove', {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
}, true);
function initTestBlock(id, events, noRemove) {
var block = document.getElementById(id);
var parent = block.querySelector('.parent');
var target = block.querySelector('.target');
target.addEventListener(events.start, function(e) {
console.log(e.type);
if (!noRemove) {
setTimeout(function() {
// Remove target
target.parentElement.removeChild(target);
}, 1000);
}
function onMove(e) {
console.log(e.type);
var pt = getCoords(e);
parent.style.left = pt.x + 'px';
parent.style.top = pt.y + 'px';
}
function onEnd(e) {
console.log(e.type);
window.removeEventListener(events.move, onMove);
window.removeEventListener(events.end, onEnd);
}
window.addEventListener(events.move, onMove);
window.addEventListener(events.end, onEnd);
});
}
// Returns pointer coordinates
function getCoords(e) {
if (e instanceof TouchEvent) {
return {
x: e.touches[0].pageX,
y: e.touches[0].pageY
};
}
return {
x: e.pageX,
y: e.pageY
};
}
window.addEventListener('selectstart', function() {
return false;
}, true);
.parent {
background: darkred;
color: white;
width: 10em;
height: 10em;
position: absolute;
}
.target {
background: orange;
width: 4em;
height: 4em;
}
#mouse .parent {
left: 0em;
}
#touch .parent {
left: 11em;
}
#touch-no-remove .parent {
left: 22em;
}
<div id="mouse">
<div class="parent">Mouse events
<div class="target">Drag here</div>
</div>
</div>
<div id="touch">
<div class="parent">Touch events
<div class="target">Drag here</div>
</div>
</div>
<div id="touch-no-remove">
<div class="parent">Touch (no remove)
<div class="target">Drag here</div>
</div>
</div>
2 回答
的确,according to the docs,
事实证明,解决方案是将
touchmove
和touchend
监听器附加到event.target
本身,例如:即使从DOM中删除了
event.target
元素,事件仍将继续正常触发并提供正确的坐标 .诀窍是隐藏元素直到触摸移动完成,但不删除它 . 以下是一些示例(在Chrome开发工具中启用触摸模式并选择一些设备或使用真实设备):https://jsfiddle.net/alexanderby/na3rumjg/