晴明的博客园 GitHub      CodePen      CodeWars     

[js][填坑] 简单模拟touch 滑动、长按

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Touch</title>
        <meta name="viewport" content="width=device-width, user-scalable=no">
    </head>

    <body>

        <div id="output" style="min-height:300px;overflow: auto;background: lightblue;">
        </div>
        <script type="text/javascript">
            (function() {
                var output = document.getElementById("output");
                var a, b;

                function handleTouchEvent(event) {
                    if (event.touches.length == 1) {
                        switch (event.type) {
                            case "touchstart":
                                //event.preventDefault();  //防止 touchend 不生效,貌似没用
                                output.innerHTML = "Touch started (" + event.touches[0].clientX + "," + event.touches[0].clientY + ")";
                                a = event.touches[0].clientY;
                                break;
                            case "touchend":
                                output.innerHTML += "<br>Touch ended (" + event.changedTouches[0].clientX + "," + event.changedTouches[0].clientY + ")";
                                break;
                            case "touchmove":
                                //event.preventDefault(); //prevent scrolling
                                output.innerHTML += "<br>Touch moved (" + event.changedTouches[0].clientX + "," + event.changedTouches[0].clientY + ")";
                                b = event.touches[0].clientY;
                                if ((a - b) > 20) {
                                    alert('boom'); //模拟向上滑动
                                }
                                break;
                        }
                    } else if (event.touches.length == 0) {
                        //chrome touchend 不生效,用 event.touches.length == 0 模拟 touchend
                        output.innerHTML += "<br>Touch ended (" + event.changedTouches[0].clientX + "," + event.changedTouches[0].clientY + ")";
                    }
                }
                output.addEventListener("touchstart", handleTouchEvent, false);
                output.addEventListener("touchend", handleTouchEvent, false);
                output.addEventListener("touchmove", handleTouchEvent, false);
            })();
        </script>
    </body>

</html>

 

posted @ 2016-02-18 13:53  晴明桑  阅读(1962)  评论(0编辑  收藏  举报