2013-10-18 30 views
1

我有一个下拉菜单,用户可以从中选择值。它目前由一个表格生成,其中每个选项都在表格中。我知道使用元素会更好,但在这一点上改变这一点需要很多工作。溢出:滚动;有没有办法默认滚动到选定的值onload?

下拉菜单显示6行,并使用“overflow:scroll”允许用户向下滚动查看其余选项。

当前,当用户选择下拉菜单时,滚动条总是从顶部开始,如果他们想要选择其中一行,他们必须向下滚动到列表的底部。

我想要的是让滚动条从他们之前选择的元素开始的方法。我知道用户以前选择的行号,并可以使用它来计算滚动条在加载时应该向下移动的像素数。

具体的HTML代码不是太重要,因为我相信这个想法可以推广到很多情况,但这里是我现在正在处理的内容:一些元素缺失,因为它们是在运行时间,但你应该能够得到我正在处理的一般想法。

<table cellspacing="0" cellpadding="2" style="width: 100%;> 
    <colgroup> 
    <col class="select_htc_col" style="font-size: 11px;"> 
</colgroup> 
    <tbody> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
      <tr style="height: 19px;"> 
    </tbody> 
</table> 

我觉得应该有一些CSS属性让滚动条不在顶部开始。

另一个想法是给每个ID,并以某种方式显示该元素。

谢谢!

回答

1

恐怕你无法通过纯粹的CSS来实现。请检查:set scrollTop and scrollLeft without javascript

你可以用jQuery来做,它有一个scrollTop()函数。此外,该函数也有一个int参数以指示/设置要滚动的位置。 http://api.jquery.com/scrollTop/

<!doctype html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8"> 
     <title>scrollTop demo</title> 
     <style> 
      p { 
       margin: 10px; 
       padding: 5px; 
       border: 2px solid #666; 
      } 
     </style> 
     <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    </head> 
    <body> 
     <p>Hello</p> 
     <p></p> 
     <script> 
      var p = $("p:first"); 
      $("p:last").text("scrollTop:" + p.scrollTop()); 
     </script> 
    </body> 
</html> 

取之。

希望它有帮助。

+0

谢谢!如果这是最简单的方法,我没有问题使用JavaScript。我会试试这个。 –