检测用户的意图是在触觉设备上点击还是向上/向下滚动页面

时间:2013-09-12 14:56:17

标签: javascript android jquery ios touch

如果用户在popup-div外点击(touchstart),我想隐藏弹出窗口。

但如果用户的意图是滚动/滑动(touchmove),我不想隐藏弹出窗口。

代码如何检测并响应这两个操作(使用或不使用jQuery)?

3 个答案:

答案 0 :(得分:3)

以下是如何执行此操作的基本示例: http://jsfiddle.net/4CrES/2/

它背后的逻辑包括检测初始触摸时间并将其保存到var

touchTime = new Date();

在touchend处理程序中从当前时间减去此时间以获得差异:

var diff = new Date() - touchTime;

使用if语句来确定触摸持续时间是否足够短以将其视为点击,或者足够长以将其视为拖动。

if (diff < 100){
    //It's a tap
}
else {
    //Not a quick tap
}

您可以通过在处理程序中执行初始触摸y位置与最终触摸y位置的类似差异来编写更强大的实现。另一种选择是比较滚动区域的scrollTop以查看它是否已滚动。

答案 1 :(得分:0)

由于点击事件在触摸事件和自定义事件时不会在移动Safari上冒泡DOM,我最近编写了一些代码来检测快速点击。

这是一个快速点击

  • 触摸事件开始和结束,屏幕没有任何移动
  • 没有滚动发生器
  • 这一切都发生在不到200ms。

如果确定触摸是“quickTap”,则TouchManager会使DOM中的触摸元素发出自定义“quickTap”事件,然后将DOM冒泡到恰好正在侦听它的任何其他元素。此代码定义并创建了触摸管理器,它将立即准备好

缺点:

  • 使用jQuery
  • 仅用一根手指设计。
  • 还从modernizr借了一些代码。 (如果您已经包含Modernizr,则可以省略该位。)

也许这有点矫枉过正,但它是我正在努力的更大代码库的一部分。

/** 
 * Click events do not bubble up the DOM on mobile Safari unless the click happens on a link or form input, but other events do bubble up.
 * The quick-tap detects the touch-screen equivalent of a click and triggers a custom event on the target of the tap which will bubble up the DOM.
 * A touch is considered a click if there is a touch and release without any movement along the screen or any scrolling.
 */

var qt = (function ($) {
    /**
     * Modernizr 3.0.0pre (Custom Build) | MIT 
     * Modernizr's touchevent test
     */
    var touchSupport = (function() {
            var bool,
                prefixes = ' -webkit- -moz- -o- -ms- '.split(' ')
            if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
                bool = true;
            } else {
                var query = ['@media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
                testStyles(query, function( node ) {
                    bool = node.offsetTop === 9;
                });
            }
            return bool;
        }()),
        MobileTapEvent = 'tapEvent';

    if(touchSupport) {
        /* Create a new qt (constructor)*/
        var startTime = null,
            startTouch = null,
            isActive = false,
            scrolled = false;

        /* Constructor */
        function qt() {
            var _qt = this,
                context = $(document);
            context.on("touchstart", function (evt) {
                startTime = evt.timeStamp;
                startTouch = evt.originalEvent.touches.item(0);
                isActive = true;
                scrolled = false;
            })
            context.on("touchend", function (evt) {
                window.ct = evt.originalEvent['changedTouches'];
                // Get the distance between the initial touch and the point where the touch stopped.
                var duration = evt.timeStamp - startTime,
                    movement = _qt.getMovement(startTouch, evt.originalEvent['changedTouches'].item(0)), 
                    isTap = !scrolled && movement < 5 && duration < 200;
                if (isTap) {
                    $(evt.target).trigger('quickTap', evt);
                }
            })
            context.on('scroll mousemove touchmove', function (evt) {
                if ((evt.type === "scroll" || evt.type === 'mousemove' || evt.type === 'touchmove') && isActive && !scrolled) {
                    scrolled = true;
                }
            });
        }

        /* Calculate the movement during the touch event(s)*/
        qt.prototype.getMovement = function (s, e) {
            if(!s || !e) return 0;
            var dx = e.screenX - s.screenX, 
                dy = e.screenY - s.screenY;
            return Math.sqrt((dx * dx) + (dy * dy));
        };
        return new qt();
    }
}(jQuery));

要使用代码,您可以将其添加到您的页面,然后只需监听quickTap事件。

<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="quick-tap.js"></script>
<script type="text/javascript">
    $(document).on('quickTap', function(evt, originalEvent) {
        console.log('tap event detected on: ', evt.target.nodeName, 'tag');
    });
</script>

evt 是quickTap事件。

evt.target 是tapped DOM元素(不是jQuery对象)。

originalEvent 是一个touchend事件,qt确定它是否是一个点击。

答案 2 :(得分:0)

您可以在touchend事件中隐藏popup-div 在touchstart事件中你记得window.scrollY 在touchend事件中,如果scrollY位置不同,则用户已滚动。