开发者

jQuery click link find div with matching id scrollTo

开发者 https://www.devze.com 2023-02-10 15:09 出处:网络
I am creating a page. I have the following HTML: <ul id=\"nav\"> <li><a href=\"#section1\">Link</a></li>

I am creating a page. I have the following HTML:

        <ul id="nav">
            <li><a href="#section1">Link</a></li>
            <li>&开发者_如何学编程lt;a href="#section2">Link</a></li>
            <li><a href="#section3">Link</a></li>
            <li><a href="#section4">Link</a></li>
            <li><a href="#section5">Link</a></li>
            <li><a href="#section6">Link</a></li>
        </ul>

        <div class="section">
            <p>Content</p>
        </div>

        <div class="section" id="section1">
            <p>Content</p>
        </div>

        <div class="section">
            <p>Content</p>
        </div>

        <div class="section" id="section2">
            <p>Content</p>
        </div>

        <div class="section">
            <p>Content</p>
        </div>

        <div class="section" id="section3">
            <p>Content</p>
        </div>

        <div class="section">
            <p>Content</p>
        </div>

        <div class="section" id="section4">
            <p>Content</p>
        </div>

        <div class="section">
            <p>Content</p>
        </div>

        <div class="section" id="section5">
            <p>Content</p>
        </div>

        <div class="section">
            <p>Content</p>
        </div>

        <div class="section" id="section6">
            <p>Content</p>
        </div>

What I would like to achieve is when a link is clicked. Use jQuery to find a div with the same id as the links href and then scroll the page to that div. Can anyone point me in the right direction? The bit I am struggling with is how to match the id to the href.

Many thanks.


Add a click event to each of the anchor tags. The use the attr function to get the href of the selected element.

I've then used the animate function to scroll to this element.

$(function(){
    $('#nav li a').click(function(){
        var divID = $(this).attr('href');
        $('html,body').animate({
            scrollTop: $(divID).offset().top 
        }, {
            duration: 'slow', 
            easing: 'swing'
        }); 
    }); 
});


You could achieve this by this way:

$('#nav li a').click(function(){
    //Scroll to targetID offsetTop.. or using the scrollTo plugin, scrolling to $($(this).attr('href'))
})

scrollTo plugin


Try something like this :

$('#nav a').click(function(){
  $($(this).attr('href')).whatyouwant();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消