问题:在列表里运用touchend事件,当手指在列表上滑动时,也会触发列表元素上的touchend事件
方案一:
/*仅适用于内容中点击元素。对于拖动等元素,需要自行在页面处理。
* 主要是绑定touchstart和touchmove事件,并判断用户按下之后手指移动了多少像素。
* 如果手指移动距离小于10像素,则还是认为用户在做点击操作。如果移动距离超过了10像素,则取消后续事件监听函数的执行。*/
// html部分
<ul>
<li class="list" style="height: 50px;background: #ccc;margin-bottom: 20px;">111</li>
<li class="list" style="height: 50px;background: #ccc;margin-bottom: 20px;">222</li>
<li class="list" style="height: 50px;background: #ccc;margin-bottom: 20px;">333</li>
</ul>
// js部分
function makeTouchableButton(ele) {
if (!ele) {
console.error("MIGlobals.makeTouchableButton 无效的元素!");
return false;
}
for (var i = 0; i < ele.length; i++) {
ele[i].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[i].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[i].addEventListener("touchend", function(evt) {
if (this.getAttribute("data-moved") == "y") {
evt.stopImmediatePropagation();
return false;
}
});
}
}
var divs = document.querySelectorAll(".list");
makeTouchableButton(divs);
for (var i =0; i < divs.length; i++) {
divs[i].addEventListener("touchend",function(){
alert("您点击我啦。");
});
}
方案二:
// html部分
<ul>
<li class="touchdiv" style="height: 50px;background: #ccc;margin-bottom: 20px;">111</li>
<li class="touchdiv" style="height: 50px;background: #ccc;margin-bottom: 20px;">222</li>
<li class="touchdiv" style="height: 50px;background: #ccc;margin-bottom: 20px;">333</li>
</ul>
// js部分
function stopTouchendPropagationAfterScroll(){
var locked = false;
window.addEventListener('touchmove', function(){
locked || (locked = true, window.addEventListener('touchend', stopTouchendPropagation, true));
}, true);
function stopTouchendPropagation(ev){
ev.stopPropagation();
window.removeEventListener('touchend', stopTouchendPropagation, true);
locked = false;
}
}
var divs = $(".touchdiv");
stopTouchendPropagationAfterScroll();
divs.on("touchend",function(){
alert("您点击我啦。");
});