[JS]javascript优化移动端OnClick事件

这个的效果会给用户带来很好的用户体验,我大致描述一下,大家应该都遇到过:当你点击一个按钮在按下的时候突然又有了其他想法,你把手指移到按钮区域以外,这个时候APP是不会有事件触发的。

这个内容在上次的HTML5学习笔记里有,但是今天写东西的时候用到了,又优化了一下,同样适用PC端。贴代码

function tap(src, cb) {
        $(src).unbind();
        var isTouchDevice = 'ontouchstart' in window || navigator.msMaxTouchPoints;
        if (isTouchDevice) {
            $(src).bind("touchstart", function (event) {
                $(this).data("touchon", true);
                $(this).addClass("pressed");
            });
            $(src).bind("touchend", function () {
                $(this).removeClass("pressed");
                if ($(this).data("touchon")) {
                    cb.bind(this)();
                }
                $(this).data("touchon", false);
            });
            $(src).bind("touchmove", function () {
                $(this).data("touchon", false);
                $(this).removeClass("pressed");
            });
        } else {
            $(src).bind("mousedown", function () {
                $(this).addClass("pressed");
                $(this).data("touchon", true);
            });
            $(src).bind("mouseup", function () {
                $(this).removeClass("pressed");
                $(this).data("touchon", false);
                cb.bind(this)();
            });
        }
    }

有时间了整理一下我的通用JS贴出来。

原文地址:https://www.cnblogs.com/flyingMonkey/p/5130498.html