简体   繁体   中英

Prevent child event from firing

I have a slider that I am currently making. I am making slow progress, but I am making progress nonetheless! Currently I have this:

http://codepen.io/r3plica/pen/mEKyGG?editors=1011#0

There are 2 things you can do with this control, the first thing is you can drag left or right. The second thing you can do is click a "point" and it will scroll to the center. The problem I have is that if I start dragging from a point, when I let go it will invoke the moveToCenter method.

I have tried to prevent this by adding

// Stop from accessing any child events
e.preventDefault();
e.stopPropagation();

to the end of the dragEventHandler , but this did not work. I also have 2 boolean values options.drag and options.start . I though I might be able to use them somehow (if the drag has started and is enabled then don't perform the moveToCenter but this didn't work either.

Do anyone have any idea how to get this to work?

Maybe this will help. You can register your events in bubbling or capturing mode, using addEventListener method. It defines orders of processing your events - child -> parent (bubbling), or vice versa (capturing).

http://www.quirksmode.org/js/events_advanced.html

So, if you use addEventListener(event, handler, true ), it will use capturing event mode.

Codepen:

http://codepen.io/anon/pen/bZKdqV?editors=1011

divs.forEach(function (div) {
      div.addEventListener('click', function(e) {
        e.stopPropagation();
        console.log('parent');
      }, true);  
  });

Be aware of browser support (IE9+). All modern browsers - yes, of course.

http://caniuse.com/#search=addeventlistener

Update

So it turned out to be easier than first approach. (no need for capturing) Check out codepen:

http://codepen.io/anon/pen/QExjzV?editors=1010

Changes from your sample: At the beginning of moveToCenter: function(e, options, animate) function

if (options.started) {
  return;
}

In if (['mouseup', 'mouseleave'].indexOf(e.type) > -1) :

setTimeout(function() {
  options.started = false;
} , 100);

instead of

options.started = false;

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM