문제

Ok, so I have the following nav with absolute urls:

<ul class="nav navbar-nav" id="main-menu">
    <li class="first active"><a href="http://example.com/" title="Home">Home</a></li>
    <li><a href="http://example.com/about.html" title="About">About</a></li>
    <li><a href="http://example.com/portfolio.html" title="Portfolio">Portfolio</a></li>
    <li class="last"><a href="example.com/contact.html" title="Contact">Contact</a></li>
</ul>

and then articles with the following data attributes:

<article class="row page" id="about" data-url="http://example.com/about.html">
    <div class="one">

    </div>
    <div class="two"

    </div>
</article>

and when you click the link in the menu I would like to ignore the fact it is a hyperlink and slide to the current article based on its attribute data-url.

I started with what I think is the obvious:

$('#main-menu li a').on('click', function(event) {
    event.preventDefault();
    var pageUrl = $(this).attr('href');

)};

and have tried find and animate but then I don't know how to reference the article with data-url="http://example.com/about.html".

Any help would be most appreciated.

Thanks

도움이 되었습니까?

해결책

Try

$('#main-menu li a').on('click', function (event) {
    event.preventDefault();
    var pageUrl = $(this).attr('href');
    var $article = $('article[data-url="' + pageUrl + '"]');
    if ($article.length) {
        $('body').stop(true).animate({
            scrollTop: $article.position().top
        })
    }
});

Demo: Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top