简体   繁体   中英

jQuery scrollTop - animation not working

Using the example found here , I'm trying the implement the same. When I click on a navigation link, it jumps to the selected div instead of sliding/scrolling.

HTML:

Navigation

<div class="span3">
        <a href="#about-me"><img class="img-circle" src="http://placehold.it/200x200/e36b23/fff/&text=About+Me+"></a>
</div>

DIV

<div class="row-fluid" id="about-me"> ... </div>

JS:

<script>
$(document).ready(function(){

    $('nav ul li a').click(function(){
        var el = $(this).attr('href');
        var elWrapped = $(el);

        scrollToDiv(elWrapped,40);

        return false;
    });

    function scrollToDiv(element, navheight){
        var offset = element.offset();
        var offsetTop = offset.top;
        var totalScroll = offsetTop - navheight;

        $('body,html').animate({
            scrollTop: totalScroll
        }, 1000);
    }
});
</script>

So it's getting to the 'clicked' div but not with the slide animation - which is what I want. Anyone have any ideas?

You do not prevent default behavior, which is to navigate ("jump") directly to the anchor point. So here it goes:

$('nav ul li a').click(function(evt){
  evt.preventDefault();
  ...
});

You need to adjust your jQuery selector to match your html classes - you aren't using the same ul / li that your cited example uses, eg

$('.span3 a').click(function(){

See here for a fiddle:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM