javascript - Scroll to element in flexbox container - Stack Overflow

admin2025-04-20  0

I am trying to autoscroll to an element in a flexbox container.

<div class="nav">
  <div class="items">
    <div ng-repeat="i in items"  scroll-on-click>
      {{i}} click me to scroll to me!
    </div>
  </div>
</div>

app.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $element) {
      $element.on('click', function() {
        $(".items").animate({scrollTop: $element.offset().top}, "slow");
      });
    }
  }
});

It scrolls to the top of the first item clicked, but after that it has a hard time scrolling. I have had something very similar in a non-flexbox container working.

Here is a plunk:

Any ideas?

I am trying to autoscroll to an element in a flexbox container.

<div class="nav">
  <div class="items">
    <div ng-repeat="i in items"  scroll-on-click>
      {{i}} click me to scroll to me!
    </div>
  </div>
</div>

app.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $element) {
      $element.on('click', function() {
        $(".items").animate({scrollTop: $element.offset().top}, "slow");
      });
    }
  }
});

It scrolls to the top of the first item clicked, but after that it has a hard time scrolling. I have had something very similar in a non-flexbox container working.

Here is a plunk:

http://plnkr.co/edit/kq40NiTqBI81KlRJBLHu?p=preview

Any ideas?

Share Improve this question edited Apr 4, 2016 at 23:29 lostintranslation asked Apr 4, 2016 at 22:10 lostintranslationlostintranslation 24.7k53 gold badges173 silver badges290 bronze badges 3
  • Happening on all browsers? Chrome seems to be working fine. – Michael Benjamin Commented Apr 4, 2016 at 22:14
  • Chrome does not work for me. When I click elements they do not always scroll to the top. Seems like if I start at the top of the list it will scroll correctly. However if I am in the middle of the list, not so much. – lostintranslation Commented Apr 4, 2016 at 22:19
  • Consider adding Javascript, jQuery and CSS tags for more attention. – Michael Benjamin Commented Apr 4, 2016 at 23:26
Add a ment  | 

1 Answer 1

Reset to default 6

Use the offsetTop property to capture the scroll value of embedded (non-root) DOM elements, like a flexbox. Good discussion here. I'm subtracting 10 to stop the divs from being cut off, do as you wish.

$(".items").animate({scrollTop: $element.prop('offsetTop') - 10}, "slow");

Working Plunker

EDIT:

To handle a header or other element, flexbox or not, just subtract its height from scrollTo (assigning an id to the header):

$(".items")
  .animate(
    {
      scrollTop: $('#' + id).prop('offsetTop') - 
        document.getElementById('header').offsetHeight - 
        10 // Store this as a .constant if it won't change

    }, "slow");

Working Plunker

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114768a285797.html

最新回复(0)