触摸事件处理程序会覆盖单击处理程序

时间:2015-01-29 15:50:09

标签: javascript jquery html angularjs touch

我在AngularJS中创建了一个自定义可拖动指令。它是jQuery事件和vanilla javascript的组合。我试图使它尽可能通用和可重复使用,它也必须是触摸友好的。

TL; DR

我无法在触摸环境中点击我的可拖动指令上的按钮。

重现的步骤:

  1. 打开codepen示例:CodePen
  2. 在Chrome上,F12,模拟iPad 3/4
  3. 通过title = works!
  4. 拖动面板
  5. 点击按钮=无警报。
  6. 更长的解释

    该指令可选地将整个元素置于可拖动状态,除非具有类"拖动句柄"放置,在这种情况下,它被用作元素的拖动句柄。我通常在引导板上使用它,因为它是一个简单的例子。

    该指令在桌面上运行良好,但是在触摸设备上,如果拖动句柄上有任何可点击的项目,则拖动处理程序会覆盖点击事件,并且它从未被调用过。

    示例HTML将是:

    <div class="panel panel-default" app-draggable>
        <div class="panel-heading drag-handle"> <!-- Drag Handle -->
            <div class="panel-title">
                Example Title
                <button onclick="alert('clicked')" class="btn btn-xs btn-primary pull-right" type="button">Click</button>
            </div>
        </div>
        <div class="panel-body">Example body</div>
    </div>
    

    因此,在桌面上,您可以拖动面板,然后单击按钮以获取警报。但是,当我在Chrome上模拟iPad 3/4(或在真正的iPad上将其拉起)时,点击永远不会被触发。

    我的指示如下。它将容器设置为绝对容器(除非容器已经固定,在这种情况下它将补偿并仍然使其可拖动。

     /*
     * @summary
     * Directive that makes an element draggable.
     * @description
     * This directive should be used in conjunction with specifying a drag handle 
     * on the element. If not, then entire element will be draggable.
     * @example
     * <div class='myDiv' app-draggable>
     *   <div class='drag-handle'>This will be the drag handle</div>
     *   <div>This will be dragged</div>
     * </div>
     */
    angular.module("app")
        .directive('appDraggable', appDraggable);
    
    function appDraggable() {
        var directive = {
            restrict: 'A',
            link: link
        };
    
        function link(scope, element) {
            var startX = 0, startY = 0, x = 0, y = 0;
            var startTop;
            var startLeft;
            var dragHandle = element[0].querySelector(".drag-handle");
            var dragHandleElement;
            /*
             * If there is a dragHandle specified, add the touch events to it.
             * Otherwise, make the entire element draggable.
             */ 
            if (dragHandle) {
                dragHandleElement = angular.element(dragHandle);
                addTouchHandlers(dragHandle);
            } else {
                dragHandleElement = element;
                addTouchHandlers(element[0]);
            }
    
            var position = element.css('position');
    
            if (position !== "absolute") {
                if (position === "fixed") {
                    // If fixed, get the start offset relative to the document.
                    startTop = element.offset().top;
                    startLeft = element.offset().left;
                    /*
                     * Explicitly set the height and width of the element to prevent
                     * overrides by preset values.
                     */ 
                    var height = parseInt(element.height(), 10);
                    var width = parseInt(element.width(), 10);
                    element.css({
                        height: height,
                        width: width
                    });
                } else {
                    // If it's not fixed, it needs to be absolute.
                    element.css({
                        position: 'absolute',
                    });
                    // And positioned originally relative to the parent.
                    startTop = element.position().top;
                    startLeft = element.position().left;
                }
            }
    
    
            /*
             * @function
             * @description
             * Add event handlers to the drag handle to capture events.
             */
            dragHandleElement.on('mousedown', function (event) {
    
                /*
                 * Prevent default dragging of selected content
                 */
                event.preventDefault();
                startX = event.pageX - x;
                startY = event.pageY - y;
                dragHandleElement.on('mousemove', mousemove);
                dragHandleElement.on('mouseup', mouseup);
            });
    
            function mousemove(event) {
    
                y = event.pageY - startY;
                x = event.pageX - startX;
                var finalTop = y + startTop;
                var finalLeft = x + startLeft;
                element.css({
                    top: finalTop + 'px',
                    left: finalLeft + 'px'
                });
            }
    
            function mouseup() {
                dragHandleElement.off('mousemove', mousemove);
                dragHandleElement.off('mouseup', mouseup);
            }
    
            function touchHandler(event) {
                var touch = event.changedTouches[0];
    
                if (event.target !== dragHandleElement) {
                    //////////////// HACK ///////////////////////////
                    //event.target.click(); // Hack as a work around.
                }
    
                var simulatedEvent = document.createEvent("MouseEvent");
                simulatedEvent.initMouseEvent({
                    touchstart: "mousedown",
                    touchmove: "mousemove",
                    touchend: "mouseup"
                }[event.type], true, true, window, 1,
                touch.screenX, touch.screenY,
                touch.clientX, touch.clientY, false,
                false, false, false, 0, null);
    
                touch.target.dispatchEvent(simulatedEvent);
                event.preventDefault();
            }
    
            function addTouchHandlers(element) {
                element.addEventListener("touchstart", touchHandler, true);
                element.addEventListener("touchmove", touchHandler, true);
                element.addEventListener("touchend", touchHandler, true);
                element.addEventListener("touchcancel", touchHandler, true);
            }
    
    
        }
        return directive;
    }
    

    您会注意到上述指令中存在黑客行为:

    if (event.target !== dragHandleElement) {
         //////////////// HACK ///////////////////////////
         //event.target.click(); // Hack as a work around.
    }
    

    如果我取消注释,它可以在触控设备上运行,因为这会检查触控目标是否为拖动手柄,如果不是,则手动点击目标。这有效,但对我来说似乎很讨厌,我真的想要一个更好的解决方案。它不返回false或stopPropagation,因为目标并不总是直接是dragHandle,但它仍然需要拖动。

    我不知道为什么这不起作用,因为它没有手动停止触摸事件的传播,因为它使用event.preventDefault而不是event.stopPropagation,但我&# 39;我确定我错过了什么。

    您可以重现here

    此外,欢迎任何其他有关如何改进上述代码以获得更多平台设备和更强大的建议!

    思想?

    谢谢!

1 个答案:

答案 0 :(得分:1)

发现问题。

我上面的touchHandler功能总是在触摸时传输“mousedown”事件,即使它更准确地说是应该传输的“点击”事件。由于我的所有事件处理程序都在寻找“点击”事件,因此他们忽略了正在传输的“mousedown”事件。

我将touchHandler功能更改为下面的功能,它就像一个魅力。

    var mouseMoved = false;
    function touchHandler(event) {
        // Declare the default mouse event.
        var mouseEvent = "mousedown";
        // Create the event to transmit.
        var simulatedEvent = document.createEvent("MouseEvent");

        switch (event.type) {
        case "touchstart":
            mouseEvent = "mousedown";
            break;
        case "touchmove":
            /*
            * If this has been hit, then it's a move and a mouseup, not a click
            * will be transmitted.
            */
            mouseMoved = true;
            mouseEvent = "mousemove";
            break;
        case "touchend":
            /*
            * Check to see if a touchmove event has been fired. If it has
            * it means this have been a move and not a click, if not
            * transmit a mouse click event.
            */
            if (!mouseMoved) {
                mouseEvent = "click";
            } else {
                mouseEvent = "mouseup";
            }
            // Initialize the mouseMove flag back to false.
            mouseMoved = false;
            break;
        }

        var touch = event.changedTouches[0];

        /*
         * Build the simulated mouse event to fire on touch events.
         */
        simulatedEvent.initMouseEvent(mouseEvent, true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

        /*
         * Transmit the simulated event to the target. This, in combination
         * with the case statement above, ensures that click events are still
         * transmitted and bubbled up the chain.
         */
        touch.target.dispatchEvent(simulatedEvent);

        /*
         * Prevent default dragging of element.
         */
        event.preventDefault();
    }

此实现会在touchmovetouchstart之间查找touchend个事件。如果有,则设置标记并发送click事件而不是mousedown事件。

它也可以与计时器一起使用,这样即使鼠标移动了一小部分它也会发送一个点击事件,但就我的目的而言,这非常有效。