简体   繁体   中英

jQuery: scroll to the top of a div that has overflow: scroll;

Codepen Link

I need on to scroll to the top of a div that has a fixed height and overflow: scroll; .

JavaScript

$('button').click(function() {
  var $target = $('aside div:first-child');
  var scrTop = Math.abs($target.offset().top);
  $('html, body').animate({
      scrollTop: scrTop
    }, 400);
  console.log($target.offset().top)
});

The issue is that console.log() returns negative integer of the offset.top method, which should not happen in normal circumstances.

I tried different approaches but couldn't find a way.

Is that even possible?

Steps to reproduce:

  1. Scroll to the bottom of the pink div with green divs inside.
  2. Click the button
  3. Open Dev Tools and see what console.log(); returns
  4. And the scroll to the top of the green div doesn't happen.

Any ideas?

只是一个主意,

$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top);

I've forked an updated your codepen here

you were getting the scrTop value incorrectly and you were scrolling the entire html document (which didn't have a scroll)

codepen JS

$('button').click(function() {
  var $target = $('aside');
  var scrTop = Math.abs($target.offset().top);
  $target.animate({
      scrollTop: scrTop
    }, 400);
  console.log(scrTop)
});

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