AngularJS ScrollTop on Click Directive. How do I stop an inner click from triggering the outer directive click.

StackOverflow https://stackoverflow.com/questions/21808928

質問

I built a directive to scroll a section into view after a delay which is to compensate for the section animating open then added functionality to stop the scroll if the user attempts to scroll the screen at all manually.

angular.module("scrollOnClick", [])
.directive('scrollOnClick', function() {
    return {
        restrict: 'A',
        link: function(scope, $elm, $window) {
            $elm.on('click', function() {
                var $viewport = $('html, body');

                $viewport.bind("scroll mousedown DOMMouseScroll mousewheel keydown", function(){
                     $viewport.stop()
                });     

        setTimeout(function () {   
            var winH = window.innerHeight
            var oSet = (winH / 2) - 222
            $viewport.animate({scrollTop: $elm.offset().top - oSet}, "easing", function(){
                $viewport.unbind("scroll mousedown DOMMouseScroll mousewheel keydown");
            }); return false;
        }, 201);
      });
   }
  }
});

My problem is I have a button inside the section that I don't want it to trigger a scrollTop animation. Any idea's how to stop it?

役に立ちましたか?

解決

Try:

$elm.on('click', function(event) {
   if (event.target == this){ //run code only when the clicked target is the current element.
    //your code

   }
}

Another solution is adding this code:

$elm.find("button").on('click',function(event){
   return false;//prevent default and stop propagation.
   //or event.stopPropagation();
});

//your code 
$elm.on('click', function() {

To use .find with selector, you may need to include jQuery

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top