简体   繁体   English

滚动到溢出div中的特定元素

[英]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). 我有一个具有溢出功能的div ,其作用类似于列表(因为在所有浏览器中自定义并保持这种方式时,真正的“选择”是一件麻烦事)。

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 . 问题是,名单很长,我想,当页面加载列表“选择”元素会或多或少地在中间div ,像推杆selected=selectedoptionselect

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") 为您的列表项之一指定特定的ID(例如:“ 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. 当您链接到此页面时,将#anchor标签#anchor到url,您的列表将被拖到具有相应ID的列表项中。

Example url : www.yourpage.com/list should become www.yourpage.com/list#anchor 网址示例: www.yourpage.com/list应该变成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. 如果使用jQuery,则可以使“选择”容器滚动到特定元素。 In this case, I add a .select class to a random li just to show how it works. 在这种情况下,我向随机li添加一个.select类,只是为了演示其工作原理。

Then, you can do the scroll on the #wraptable container by the number of pixels the .selected element is according to its parent. 然后,您可以按.selected元素根据其父元素的像素数在#wraptable容器上滚动。

$(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: 要添加jQuery,请在页面顶部添加库:

<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: 如果您不想使用jQuery,则仍然可以通过纯JavaScript来实现相同的结果,但是需要更多代码:

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: 如果您只是想将滚动条带到中间,则可以尝试以下js:

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

It takes the scroll of the #wraptable to the middle. 它将#wraptable的滚动滚动到中间。

FIDDLE DEMO 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM