我正在尝试使用以下模式实现类似拖拽的功能:
- 订阅标记指针按下事件。
- 当按下事件触发时,订阅 Window 指针移动和释放事件,并删除标记。
- 在移动时执行一些操作。
- 当释放事件触发时,取消订阅移动和释放事件。
这对于鼠标事件有效,但对于触摸事件无效。它们在触摸开始目标元素被移除后不再触发。我尝试使用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>