手机端给父元素绑定了长按事件,但是子元素的点击事件不被触发的解决方法——事件委托

今天遇到一个问题,手机端给父元素绑定了长按事件,但是子元素的点击事件不被触发

需要实现的功能

  1. 子元素需要点击
  2. 父元素需要  长按  高亮显示
  3. 父元素高亮时有自己的点击事件   并且  不触发子元素的点击事件
  4. 点击其他位置,取消高亮显示

页面展示


代码如下


<!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事件是不起作用的,需要使用事件委托进行事件的绑定

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值