我尝试基于指针事件创建拖放功能以支持触摸屏。我的代码似乎可以在Firefox(移动和触摸)中正常运行, 在chrome中,它可以与鼠标一起使用,但是一旦指针离开所拖动的元素,便会在触摸屏上停止工作。
我试图分析事件。我唯一注意到的是,在拖动元素离开时会触发“ pointercancel”事件。
<html>
<head>
<style type="text/css">
#target{
width: 400px;
height: 100px;
border: 1px solid #000;
}
#target.over{
background-color: #fef0f0;
}
#box{
width: 50px;
height: 50px;
background-color: #ff0000;
}
</style>
<script type="text/javascript">
let dragDrop = {};
dragDrop.dragDrop = function(){
let self = this;
this.vars = {
target: null,
box: null,
pointerDragMoveBind: null,
pointerDragEndBind: null,
pointerDragEnterBind: null,
pointerDragLeaveBind: null,
pointerDropBind: null
};
};
dragDrop.dragDrop.prototype = {
init: function(){
let self = this;
self.vars.target = document.getElementById("target");
self.vars.box = document.getElementById("box");
self.vars.pointerDragMoveBind = self.onPointerDragMove.bind(self);
self.vars.pointerDragEndBind = self.onPointerDragEnd.bind(self);
self.vars.pointerDragEnterBind = self.onPointerDragEnter.bind(self);
self.vars.pointerDragLeaveBind = self.onPointerDragLeave.bind(self);
self.vars.pointerDropBind = self.onPointerDrop.bind(self);
self.vars.box.addEventListener("pointerdown", self.onPointerDragStart.bind(self));
console.log(Date.now() + " Initialized");
},
onPointerDragStart: function(event){
let self = this;
console.log(Date.now() + " Drag Start");
document.addEventListener("pointermove", self.vars.pointerDragMoveBind);
document.addEventListener("pointerup", self.vars.pointerDragEndBind);
self.vars.target.addEventListener("pointerenter", self.vars.pointerDragEnterBind);
self.vars.target.addEventListener("pointerleave", self.vars.pointerDragLeaveBind);
self.vars.target.addEventListener("pointerup", self.vars.pointerDropBind);
},
onPointerDragMove: function(event){
console.log(Date.now() + " Drag Move");
},
onPointerDragEnter: function(event){
let self = this;
console.log(Date.now() + " Drag Enter");
self.vars.target.classList.add("over");
},
onPointerDragLeave: function(event){
let self = this;
console.log(Date.now() + " Drag Leave");
self.vars.target.classList.remove("over");
},
onPointerDrop: function(event){
let self = this;
console.log(Date.now() + " Drop");
self.vars.target.classList.remove("over");
},
onPointerDragEnd: function(event){
let self = this;
console.log(Date.now() + " Drag End");
document.removeEventListener("pointermove", self.vars.pointerDragMoveBind);
document.removeEventListener("pointerup", self.vars.pointerDragEndBind);
self.vars.target.removeEventListener("pointerenter", self.vars.pointerDragEnterBind);
self.vars.target.removeEventListener("pointerleave", self.vars.pointerDragLeaveBind);
self.vars.target.removeEventListener("pointerup", self.vars.pointerDropBind);
}
};
window.addEventListener("load", function(){
let ctrl= new dragDrop.dragDrop();
ctrl.init();
});
</script>
</head>
<body>
<div id="target"></div>
<div id="box"></div>
</body>
</html>
我认为鼠标和触摸的处理方法相同。 我不想使用触摸事件,因为不提供输入和离开元素。
有人知道出什么问题了吗?