简体   繁体   中英

Links jump to top and bottom but smooth scrolling doesn't work

Links jump to bottom and top but won't smooth scroll even though I'm sure JS is working.

JS:

$.fn.ready(function() {

            // Smooth scroll to top.
            $("a[href=#top]").live("click", function(e) {
                $("html,body").animate({scrollTop:0}, 1000);
                e.preventDefault();
            });

            // Smooth scroll to bottom.
            $("a[href=#bot]").live("click", function(e) {
                $("html,body").animate({scrollTop:$(document).height()}, 1000);
                e.preventDefault();
            });
        });

HTML:

 <a href="#bot" id="botlink" title="Go to bottom">↓</a>
 <a href="#top" id="toplink" title="Go to top">↑</a>

I guess you're using an old version of jQuery if you use "live" event. Since you want to go on top/bottom, you know that they're on certain positions ( top = 0, bottom = document.height ). A working jquery code will be like :

jQuery(document).ready(function($){

  $('#botlink').add( $('#toplink') ).on( 'click', function( e ){
    e.preventDefault();

    var $btn = $(this).attr( 'id' ).replace('#', '');
    var move_to = $btn === 'botlink' ? $(document).height() : 0;

    $('body').animate({
      scrollTop : move_to
    }, 'slow');

  });

});

The code above checks when user clicks #botlink or toplink . Inside move_to variable it checks which button was clicked ( read about "short if" ) and calculate when page should go. To have a working effect, you need to animate both, html and body .

Actuall it works just on body . You also have a js fiddle here (i've foced body to grow on 1200px to be able to see the effect)

check this fiddle it might help you

Js Fiddle

$("a[href=#top]").on("click", function (e) {
    //alert("top")
    $('html, body').animate({
        'scrollTop': 0
    }, 1000)
    event.preventDefault();
});

// Smooth scroll to bottom.
$("a[href=#bot]").on("click", function (e) {
    // alert("bottom")
    var a = $(document).height()
    $('html, body').animate({
        'scrollTop': a + 'px'
    }, 1000)
    event.preventDefault();
});

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