jQuery滚动到ID脚本只向下滚动

jQuery scroll to ID script only scrolling down

本文关键字:滚动 ID jQuery 脚本      更新时间:2023-09-26

我使用以下命令使任何具有.jump-link类的锚滚动到它在href属性中引用的ID:

// Scroll to ID
$('.jump-link').click(function () {
    var el = $(this).attr('href'),
        elWrapped = $(el);
    scrollToId(elWrapped, 40);
    return false;
});
function scrollToId(element, navheight) {
    var offset = element.offset(),
        offsetTop = offset.top,
        totalScroll = offsetTop - navheight;
    $('body,html').animate({
        scrollTop: totalScroll
    }, 500);
}

不幸的是,虽然它似乎只工作滚动的页面。我还希望脚本工作滚动页面

试试这个…这将是工作。

$(".jump-link").click(function(){
 var id = $(this).attr('href');
        $('html, body').animate({scrollTop: $("#"+id).offset().top}, 2000);
});

代码如下

$(function() {
    $('ul.nav a').bind('click',function(event){
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1200);
        event.preventDefault();
    });
}); 
<script type="text/javascript">
        jQuery(document).ready(function($) {
            $(".scroll").click(function(event){     
                event.preventDefault();
                $('html,body').animate({scrollTop:$(this.hash).offset().top},1200);
            });
        });
    </script>