简体   繁体   中英

How can I scroll to an element inside a scrollable div?

I have a parent container which has two child elements. The left element is a list of items returned from a database query. The parent container has a fixed height, so any items returned in the left panel are scrollable within that left panel, not the body.

When navigating to this page, I would like for the left panel to be positioned at the point of a matching element ID. This ID i will handle through Angular's routing subscriptions, but for demo purposes I have hard coded it here.

I have tried the code below (primarily the JS) with no luck. Any assistance would be greatly appreciated.

  var list = document.getElementById("list"); var targetLi = document.getElementById('myID'); list.scrollTop = (targetLi.offsetTop - 50); 
 #wrapper { width:1280px; height:600px; border:1px solid #d9d9d9; border-radius:5px; display:flex; margin:20px auto; } #list { width:200px; height:100%; border-right:1px solid #d9d9d9; display:flex; overflow:hidden; } #right span { color:#999; font-size:12px; font-family:helvetica; } ul { width:100%; margin:0; padding:0; list-style:none; overflow-y: scroll; } li { width:100%; padding:20px 10px; box-sizing:border-box; border-bottom:1px solid #d9d9d9; display:block; font-family:helvetica; color:#666; } 
 <div id="wrapper"> <div id="list"> <ul> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li> Item </li> <li id="myID"> Item with ID </li> </ul> </div> <div id="right"> <button id="button">Demo purposes button</button> <span> Note: this would instead be called in 'ngAfterViewInit' or after the firestore query has completed. </div> </div> 

The best (and AFAIK only) option that will work across all browsers is to implement a hidden input element (like a checkbox for example) and set the focus to that element. This way the browser will scroll the container so that the focused input is visible. The trick is not to set the styling to display: none but only make the element optically invisible, for example:

opacity: 0;
width: 0;
height: 0;
display: block;

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