单击列表滚动到该部分

时间:2013-02-21 15:23:36

标签: javascript jquery html

当我点击侧边栏列表中的项目时,我想滚动到相应的.cinematography_box,我有这个标记:

就像列表中的第一项>转到>第一,.cinematography_box div等等,第二,第三等

实现这一目标的最佳方式是什么?

            <div id="sidebar" class="clearfix">
                <ul>
                    <li>
                        <a id="aboutlink" href="javascript:void(0)" >CINEMATOGRAPHY LIST</a>
                    </li>
                    <li>
                        <a href="javascript:void(0)">FIRST ITEM</a>
                    </li>
                    <li>
                        <a href="javascript:void(0)">SECOND ITEM</a>
                    </li>
                    <li>
                        <a href="javascript:void(0)">THIR ITEM</a>
                    </li>
                </ul>
            </div>

                <div id="gallery" class="cinematography clearfix">

                    <div class="cinematography_box clearfix">
                        <div class="cinematography_item">
                        </div>
                        <div class="cinematography_info">
                            <p>Lorem Ipsum</p>
                        </div>
                    </div>

                    <div class="cinematography_box clearfix">
                        <div class="cinematography_item">
                        </div>
                        <div class="cinematography_info">
                            <p>Lorem Ipsum</p>
                        </div>
                    </div>

                    <div class="cinematography_box clearfix" >
                        <div class="cinematography_item">
                        </div>
                        <div class="cinematography_info">
                            <p>Lorem Ipsum</p>
                        </div>
                    </div>

                </div>

2 个答案:

答案 0 :(得分:1)

定义每个元素:

<li data-target="one">
   <a href="javascript:void(0)">THIR ITEM</a>
</li>

<div class="cinematography_info" data-pos="one">
    <p>Lorem Ipsum</p>
</div>

使用jQuery你可以这样做:

$(document).ready(function(){
    $("li").click(function() {
       scrollTo($(this).attr("data-target"));
    });
});


function scrollTo(target){
    var tagScroll = $(".cinematography_info[data-pos='"+ target+"']");
    $('html,body').animate({scrollTop: tagScroll .offset().top},'slow');
}

参见我做过的例子: http://jsfiddle.net/NfwEv/9/

答案 1 :(得分:0)

首先,提供三个div代码ID,例如item1item2item3

这样,您可以将a代码更改为:

<li>
    <a href="#item1">FIRST ITEM</a>
</li>
<li>
    <a href="#item2">SECOND ITEM</a>
</li>
<li>
    <a href="#item3">THIR ITEM</a>
</li>