문제

I have a page with many elements with a callback bound to the click event on each one.

The page is bigger than the viewport and the user may scroll the standard way (using the mouse-wheel, scroll bars...)

Now I need to implement a pan mode, giving the user another way to scroll the page:

The user clicks, drags with mouse-down and the page scrolls.

I implemented this easily registering mousedown, mousemove and mouseup on the body element. As the user drags I scroll the window with window.scrollTo()

The problem: as the page moves under the mouse pointer, if the user pan the page clicking on an element then the mousedown and the mouseup occurr on that same element and this triggers a click event too on that element after the mouseup.

This off course is unwanted.

The click event is on a child element (mouse dowm-move-up are on body) so stopPropagation doesn't help.

Question: at the end of the mouseup callback, when actually a drag occurred (I can check this comparing initial and final mouse coordinates), can I prevent the click event to trigger?

도움이 되었습니까?

해결책

You can do this easily by simply canceling the click event in the capture phase of the body:

document.body.addEventListener("click", allowClick, true);
function allowClick(event) {
    if (panMode) {
        event.stopPropagation();
    }
}

See this fiddle for an example of ignoring a click based on a global flag. (Tested in the latest Firefox, Chrome and IEs.)

See javascript.info for a clear description of the capture and bubble phases of events in Javascript.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top