简体   繁体   中英

Scroll to element in flexbox container

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?

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

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