今天遇到一个问题,手机端给父元素绑定了长按事件,但是子元素的点击事件不被触发
需要实现的功能
- 子元素需要点击
- 父元素需要 长按 高亮显示
- 父元素高亮时有自己的点击事件 并且 不触发子元素的点击事件
- 点击其他位置,取消高亮显示
页面展示
代码如下
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.main{width: 217px; height: 167px;background: #ddd; text-align: center; padding: 10px; border-radius: 4px; margin: 30px auto;}
.area-active{background:aquamarine;}
span{ background: red; color: #fff; padding: 4px 10px; border-radius: 4px;}
</style>
</head>
<body>
<section class="main">
<p>占位置占位置占位置</p>
<p>占位置占位置占位置</p>
<p>占位置占位置占位置</p>
<span id="son">点击我</span>
</section>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function () {
$(".main").on({
touchstart: function(ev){
timeOutEvent = setTimeout("longPress()",500);
ev.preventDefault();
},
touchmove: function(){
clearTimeout(timeOutEvent);
timeOutEvent = 0;
},
touchend: function(ev){
clearTimeout(timeOutEvent);
if(timeOutEvent!=0){
// 点击事件
if($(this).hasClass("area-active")){
alert("区域长按高亮之后的点击事件");
}
}
return false;
}
})
$(".main").on("touchend" ,"span",function () {
if($(this).parent(".main").hasClass("area-active")) return true;
alert("子元素点击");
});
//点击其他区域取消高亮
$(":not(area-active)").on("click",function (ev) {
ev.preventDefault();
$(".area-active").removeClass("area-active");
});
});
// 长按事件触发 区域高亮显示
function longPress(){
timeOutEvent = 0;
$(".main").addClass("area-active");
}
</script>
</body>
</html>
注意事项
在写子元素的点击事件的时候,如果直接绑定click事件是不起作用的,需要使用事件委托进行事件的绑定