触摸事件处理程序重写单击处理(Touch event handler overrides click

2019-10-21 16:59发布

我创造了AngularJS自定义拖动指令。 这是jQuery的事件和香草的JavaScript的组合。 我试图把这作为通用的,可重复使用成为可能,而且还必须是触摸友好。

TL; DR

我不能点击我的触摸环境拖动指令的按钮。

重现步骤:

  1. 打开codepen例如: CodePen
  2. 在Chrome,F12,模仿iPad的3/4
  3. 通过标题拖动面板=作品!
  4. 点击按钮=没有警报。

更详细的解释

该指令任选地使整个元件它放置在拖动,除非与类“拖柄”的元素被放置,在这种情况下被用作拖动手柄的元件。 我通常使用这种与引导板,因为它是一个简单的例子。

该指令适用于台式机大,但是在触摸设备上,如果有一个拖动手柄任何可点击项目,拖动处理程序重写click事件和它永远不会被调用。

例如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.
}

如果我取消这个,它工作在触摸设备上,因为这会检查是否触摸圆盾是dragHandle,如果它不是,请手动点击目标。 这工作,但似乎讨厌我,我真的想更好的解决方案。 因为目标是直接不总是dragHandle它不会返回false或stopPropagation,但它仍然需要进行拖动。

我不知道为什么会这样是不行的,因为它没有手动停止触摸事件的传播,因为它使用event.preventDefault代替event.stopPropagation,但我敢肯定,我失去了一些东西。

您可以复制在这里 。

此外,关于如何提高上面的代码中任何其他建议要多平台设备无关的或更稳健的欢迎!

思考?

谢谢!

Answer 1:

发现这个问题。

touchHandler功能就永远传输上触碰的“鼠标按下”事件,即使是更准确的“单击”事件应该被传递。 因为我所有的事件处理程序正在寻找一个“click”事件,他们忽略了正在发送的“鼠标按下”事件。

我改变了我的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();
    }

这实现查找一个touchmove事件之间touchstarttouchend 。 如果有一个,那么它设置一个标志,并发送一个click事件,而不是mousedown事件。

它也可以配合使用,一个定时器,使得即使鼠标移到少量它会发送一个click事件,但我的目的,这种奇妙的作品。



文章来源: Touch event handler overrides click handlers