chenyinkai / blog

学习笔记,技术心得,疑难困惑,生活总结。喜欢的请star。。
42 stars 1 forks source link

自定义事件以及移动端长按事件实现 #25

Open chenyinkai opened 6 years ago

chenyinkai commented 6 years ago

随便开个头

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div{
            width: 100px;
            height: 100px;
            background-color: red;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div>长按事件</div>
    <div>三击事件</div>
    <script>
        let oDiv = document.getElementsByTagName('div')[0];
        let timer = '';

        oDiv.addEventListener('longTap', function (e) {
            console.log(e);
            console.log('长按事件触发')
        }, false);

        var event = new CustomEvent('longTap', { 'data': 'detail' });

        oDiv.ontouchstart = function () {
            console.log('ontouchstart');
            timer = setTimeout(() => {
                console.log('longTap'); //长按状态
                oDiv.dispatchEvent(event);
            }, 1000);
        }
        oDiv.ontouchmove = function () {
            console.log('ontouchmove');
            clearTimeout(timer);
        }
        oDiv.ontouchend = function () {
            console.log('ontouchend');
            clearTimeout(timer);
        }
    </script>

    <script type="text/javascript">
        let oDiv1 = document.getElementsByTagName('div')[1];
        oDiv1.addEventListener('tripleclick', function (event) {
            console.log('三击')
        }, false);

        var e = new Event('tripleclick');

        var counter = 0;
        oDiv1.onclick = function () {
            setTimeout(function () { counter = 0; }, 500);
            if (++counter == 3) {
                oDiv1.dispatchEvent(e);
            }
        }
    </script>
</body>

</html>