事件点透 案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件点透</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        body {
            position: relative;
        }
        #box2 {
            width: 200px;
            height: 200px;
            background: cyan;
        }
        #box1 {
            width: 100px;
            height: 100px;
            background: purple;
            position: absolute;
            left: 0;
            top: 0;
        }
        #box3 {
            width: 250px;
            height: 250px;
            background: blue;
        }
    </style>
</head>
<body>
    <div id="box1"></div>
    <div id="box2"></div>
    <script type="text/javascript">
        const box1 = document.getElementById('box1')
        const box2 = document.getElementById('box2')
        box2.addEventListener('click', function() {
            console.log('box2')
        })
        box1.addEventListener('touchstart', function(ev) {
            console.log('box1')
            ev.preventDefault() //点透解决办法 阻止默认行为
            this.style.display = 'none'
        })

        /**
         * 当用户手指接触到box1时,
         * 1、会触发touchstart和click两个事件,先触发touchstart事件
         * 2、在touchstart里隐藏box1
         * 3、click事件的触发有200-300ms的延时
         * 4、等到click事件要触发时,发现只有box2了(box1被隐藏了)
         * 5、所以,就只能触发box2的click事件
         * 冒泡:是元素之间存在父子关系
         * 点透:元素之间没有父子关系,只是由于click在移动端里有200-300ms的延时造成的
         * ev.preventDefault() 阻止默认行为
         * ev.stopPropagation() 阻止默认冒泡
         */
    </script>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值