简体   繁体   中英

Scroll if div is hidden by overflow

I'm looking detect when a div with class '.selected' is below the bottom of its container div (hidden by overflow:hidden). If it is, scroll down the contents of the container to reveal the next 'page', either by scrolling the equivalent of the container's height or by scrolling until the '.selected' is at the top of it's container again.

What would be the best way to go about doing this?

I used scrollTo and some of the math from the link I posted in the comment to make this:

var top = it.position().top; 
var bd = top + it.height();     
var ch = $('.tab-demo-content').height();     
if(bd>ch){  //if focused item isn't visible, scroll to it
    $(it).closest('.tv-container-vertical').scrollTo(it,500);   //this finds its parent container and scrolls it
}
  • bd =distance from top of container to selected item's bottom
  • ch = content container height

The appropriate native (non-jquery) javascript code is:

element.scrollIntoView(); // Equivalent to element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean arguments
element.scrollIntoView(scrollIntoViewOptions); // Object argument

(see https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView )

most modern browsers support scrollIntoViewIfNeeded() too:

element.scrollIntoViewIfNeeded()

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