JavaScript - WebAPI - 注册/移除多个同名事件(addEventListener)

1.1-addEventListener注册事件

<!DOCTYPE html>
<html lang="zh-CN">

<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>Document</title>
</head>

<body>
    <div class="box">我是小马哥</div>

    <script>
        // 点击事件
        const box = document.querySelector('.box')

        // on点击事件
        box.onclick = function () {
            box.style.backgroundColor = 'red'
        }

        // 同名事件: on是覆盖
        box.onclick = function () {
            box.style.height = 100 + 'px'
        }

        // 独立方式: addEventListener('事件类型,不带on',回调函数)

        box.addEventListener('click', function () {
            box.style.backgroundColor = 'red'
        })
        // addEventListener与on事件不冲突

        // addEventListener可以添加多个同名事件
        box.addEventListener('click', function () {
            box.style.borderRadius = '50%'
        })

        // 回调函数可以有名
        box.addEventListener('click', myClick)

        function myClick() {
            box.style.textAlign = 'center'
        }

        // 总结
        // 元素.addEventListener('事件类型',回调函数, 触发阶段)
        // 与on事件是独立的: 可以添加多个(为了让事件独立, 不去修改原有代码: 自己独立增加事件处理效果)
        // 事件独立的好处: 方便去掉
    </script>
</body>

</html>

1.2-removeEventListener移除事件


```html
<!DOCTYPE html>
<html lang="zh-CN">

<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>Document</title>
</head>

<body>
    <div class="box">我是小马哥</div>

    <script>
        // on事件清理很容易
        // onclick = function(){}     onclick = null

        // addEventListener添加的事件,只能有removeEventListener清理
        const box = document.querySelector('.box')

        box.addEventListener('click', function () {
            box.style.backgroundColor = 'red'
        })

        // 清理: box.removeEventListener('click事件类型',回调函数), 必须指定回调函数
        box.removeEventListener('click', function () {
            box.style.backgroundColor = 'red'
        })
        // 清理无效: 函数匹配不上, 匿名回调无法清除(永远匹配不到)


        box.addEventListener('click', myClick)
        function myClick() {
            box.style.height = 200 + 'px'
        }

        // 清理: 只有有名回调可以被清理
        box.removeEventListener('click', myClick)
    </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Henry_ww

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值