简体   繁体   中英

Scroll to specific element in overflowing div

I have a div with overflow that acts like a list (since a real "select" is a pain in the arse when customizing and keeping it that way in all browsers).

The Problem is, the list is long and I would like that when the page loads the "selected" element of the list would be more or less in the middle of the div , something like putting selected=selected to a option in a select .

Here is a Fiddle

Thanks in advance.

You can use an anchor :

  1. give a specific id to one of your list items (example: "anchor")
  2. when you link to this page, add the hashtag #anchor to the url and you list will be scolled to the list item with corresponding id.

Example url : www.yourpage.com/list should become www.yourpage.com/list#anchor

This DEMO will show you.

<li id="anchor"><span>12 years</span> ... </li>

<a href="#anchor">anchor link</a>

editable fiddle

If you use jQuery you can make the "select" container to scroll to a specific element. In this case, I add a .select class to a random li just to show how it works.

Then, you can do the scroll on the #wraptable container by the number of pixels the .selected element is according to its parent.

$(function(){   
    var offsetSelectedElement = $(".selected").position().top;
    $("#wraptable").scrollTop(offsetSelectedElement);
});

DEMO

EDIT:

To add jQuery simple add the library in the head section of your page:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    ...
 </html>

If you don't want to use jQuery though, you still can achieve the same result through pure javascript, but it's more code:

var offsetSelectedElement = document.getElementsByClassName("selectedItem")[0];
var wrappable = document.getElementById("wraptable");
wrappable.scrollTop =  offsetSelectedElement.offsetTop;

DEMO

If you are just trying to take the scroll to the middle, perhaps you could try this js:

 document.getElementById('wraptable').scrollTop = document.getElementById('wraptable').scrollHeight / 2;

It takes the scroll of the #wraptable to the middle.

FIDDLE DEMO

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