js实现单击事件、连续事件,两次以上自己去判断添加

js种实现单击事件、连续事件以及其他事件,防止事件穿透。

华为鸿蒙版本的在我的文章列表中,原生Java语言实现单击、连续点击事件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试单击双击事件</title>
</head>
<body>
<button onclick="singleSeries()">点击测试</button>
<script>
    //计时器
    let timer = null;
    //延迟时间
    let waitTime = 200;
    //计数
    let count = 0;
    //上一次时间:默认值打开为当前打开页面时间
    let lastTime = new Date().getTime();

    //单击事件和连续事件
    function singleSeries() {
        let currentTime = new Date().getTime();
        let cha = currentTime - lastTime;
        //该段判断逻辑是防止setTimeout种是连续的时候count计数等于0的时候出现了连续事件偶发出现单击事件
        if (cha < waitTime) {
            if (count == 0) {
                //防止偶发出现单击事件,将数值加1跳出判断1的条件避免事件冲突
                count = count + 2;
            } else {
                //连续事件直接加1
                count = count + 1;
            }
        } else {
            //单击事件
            count = 1;
        }
        lastTime = new Date().getTime();
        // clearTimeout(timer);//如果需要判断点击几次的请打开该注解,阻止连续事件产生。具体实根据下面(code do)现自己想要逻辑可以
        timer = setTimeout(function () {
            clearTimeout(timer);
            //判断点击次数
            if (count == 1) {
                //code do
                console.log("单击事件")
            } else {
                //code do
                console.log("连续事件")
            }
            count = 0;
        }, waitTime);
    }

    //执行方法
    // document.getElementById("事件绑定id").addEventListener('click', singleSeries)
</script>
</body>
</html>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我来秋风扫落叶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值