js 短时间内连续点击一定次数,触发某个事件

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

<body>
    <h1>快速点击5次,显示;再点5次,隐藏</h1>
    <button id="btn">点击</button>
    <script>
        function callback1() {
            console.log('显示');
        }
        function callback2() {
            console.log('隐藏');
        }

        function multipleClick(element, callback1, callback2) {
            const btn = document.querySelector(element);
            let num = 0;
            let lastTime = 0;
            let isShow = false;
            btn.addEventListener('click', () => {
                const now = Date.now();
                if (now - lastTime < 500) {
                    num++;
                } else {
                    num = 1;
                }
                lastTime = now;
                if (num === 5) {
                    num = 0;
                    lastTime = 0;
                    isShow = !isShow;
                    isShow ? callback1() : callback2();
                }
            });
        }

        multipleClick('#btn', callback1, callback2);
    </script>
</body>

</html>

效果如下:
js 短时间内连续点击一定次数,触发某个事件_第1张图片

你可能感兴趣的:(javascript,前端,开发语言)