简体   繁体   中英

Javascript or html - scroll to a div inside scrollable div

I have a scrollable div (800px x 400px). Inside is 500 smaller divs (100px x 80px), so it's a long scrollable one. Every smaller div has a id. I want to scroll to a specific div when i press a button.

I have tried some like

$("#outerDiv").scrollTop() = $("#innerDiv").scrollTop();

But i don't know if scrollTop is the right method at all? (and i know i don't use it correct)

Is there any intuitive way to do this in javascript (prefered) or just plain html?

Using Javascript

document.getElementById('outerDiv').scrollTop = document.getElementById('innerDiv').offsetTop;

Scroll Top If you want to scroll the contents of an element, use the scrollLeft and scrollTop properties - Link

Offset Top The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node. MDN -Link

Fiddle

  1. You cannot assign the return value of a method to something else. Right value cannot be evaluated.

    $("#outerDiv").scrollTop() = something is wrong

  2. What you want should be achievable by setting the enclosing container's scrollTop to a child element's offset to the parent.

    $("#outerDiv").scrollTop($("#innerDiv").position().top);

You need to set the scrollTop() of the outer div to the position().top of the inner div . Also your syntax for setting scrollTop is a little off. Try this:

$("#outerDiv").scrollTop($("#innerDiv").position().top);

Example fiddle

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