在我的情况下如何滚动div

在我的情况下如何滚动div

本文介绍了在我的情况下如何滚动div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小的功能,用户可以单击左侧的nav链接,右侧的div将滚动到对应的框.

I am trying to create a small feature that user can click the left nav link and the right div will scroll to correspond box.

例如,用户单击第二个链接,右侧的div将滚动到该div内部的第二个box.

For example, user clicks second link, the right div will scroll to the second box inside that div.

这是HTML:

<div id='nav'>
   <ul>
     <li><a id='link1' class='link' href='#'>test 1</a><li>
     <li><a id='link2' href='#'>test 2</a><li>
     ...
     <li><a id='link16' href='#'>test 16</a><li>
  </ul>
</div>

<div id='items'>
    <div id='link1-test' class='box'>
        test 1
     </div>
    <div id='link2-test' class='box'>
        test 2
     </div>
   ...
     <div id='link16-test' class='box'>
        test 16
     </div>
</div>

这是JavaScript:

Here is the javascript:

$('#nav a').on('click', function(){

    var id=$(this).attr('id')
    alert(id)

$('#items').animate({
      scrollTop: $('#'+id+'-test').offset().top
           }, 700);
    })

http://jsfiddle.net/BPB7z/3/

我的问题是我的代码似乎不起作用,因为右div中的boxes位置一直在变化.我不确定如何解决这个问题,这困扰了我一段时间.有人可以帮我这个忙吗?非常感谢!

My problem is that my codes don't seem to work because the boxes position inside the right div changes all the time. I am not sure how to solve this and it's been bothering me a while. Can someone please help me out on this? Thanks a lot!

推荐答案

滚动父div时,每个div的偏移量都在变化,您只需通过获取目标div的偏移量并添加当前父对象进行调整即可. div的滚动位置.只需在您的代码中更改一行就可以了.从此更改animatescrollTop选项:

The offset of each div is changing when you scroll the parent div, you just need to adjust for that by getting the target div's offset, and adding the current parent div's scroll position. Just change one line in your code and it will work. Change your scrollTop option for animate from this:

scrollTop: $('#'+id+'-test').offset().top

对此:

scrollTop: $('#'+id+'-test').offset().top + $('#items').scrollTop()

这是一个有效的示例: http://jsfiddle.net/BPB7z/7/

Here is a working example: http://jsfiddle.net/BPB7z/7/

这篇关于在我的情况下如何滚动div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:27