您的位置:首页 > 移动开发

移动端touchstar、touchmove、touchend 事件如果页面有滚动时不让触发 touchend 事件。

2016-12-12 18:48 399 查看
/*仅适用于内容中点击元素。对于拖动等元素,需要自行在页面处理。
* 主要是绑定touchstart和touchmove事件,并判断用户按下之后手指移动了多少像素。
* 如果手指移动距离小于10像素,则还是认为用户在做点击操作。如果移动距离超过了10像素,则取消后续事件监听函数的执行。*/

<script type="text/javascript">
function makeTouchableButton(ele) {
if (!ele) {
console.error("MIGlobals.makeTouchableButton 无效的元素!");
return false;
}

ele.addEventListener("touchstart", function(evt){
this.setAttribute("data-moved", "n");
var p = evt.touches[0];
this.setAttribute("data-touch-start-clientx", p.clientX);
this.setAttribute("data-touch-start-clienty", p.clientY);

});

ele.addEventListener("touchmove", function(evt){
if (this.getAttribute("data-moved") == "y") return false;

var p = evt.touches[0];
var startClientX = parseInt(this.getAttribute("data-touch-start-clientx"), 10);
var startClientY = parseInt(this.getAttribute("data-touch-start-clienty"), 10);
var deltax = p.clientX - startClientX;
var deltay = p.clientY - startClientY;
if (Math.abs(deltax) > 10 || Math.abs(deltay) > 10) {
this.setAttribute("data-moved", "y");
}
});

ele.addEventListener("touchend", function(evt) {

if (this.getAttribute("data-moved") == "y") {
evt.stopImmediatePropagation();
return false;
}
});

}

var divs = document.querySelector(".touchdiv");
makeTouchableButton(divs);
divs.addEventListener("touchend",function(){
console.log("您点击我啦。");
});
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐