如何使用scollTop函数来启用Bootstrap平滑滚动

How can I use the scollTop function to enable smooth scrolling with Bootstrap?

本文关键字:Bootstrap 平滑 滚动 启用 何使用 scollTop 函数      更新时间:2023-09-26

我已经创建了一个自定义的"subnavbar",它位于bootstrap的导航栏下面。它基于wrapbootstrap中的代码。

我想使用scrolltop启用平滑滚动。我有以下Javascript:

 $(document).ready(function(e) {
        $('#subnav').bind('click', function(e) {
            e.preventDefault();
            $('html,body').animate({scrollTop: $(this.hash).offset().top});                                                         
        });
    });

然而,我似乎不能使它工作。我是否使用了错误的#引用?下面是一个bootply: http://bootply.com/62720

下面的HTML片段:

                     <!-- Subnav bar -->                
                     <div class="subnav subnav-fixed">
                        <ul class="nav nav-pills">
                           <li><a href="#overview">Overview</a></li>
                           <li><a href="#opening-hours">Opening hours</a></li>
                        </ul>
                     </div>
<section id="Overview">          
<h3>OVERVIEW</h3>

谢谢

很容易犯的错误#subnav"应该是"。Subnav:首先因为Subnav是类,其次因为你想把点击绑定到链接

这样就可以了。当没有offset()

时,将top设置为0
$('.subnav li a').bind('click', function(e) {
    e.preventDefault();
    var hashTag = this.hash;
    var top = 0;
    if ($(hashTag).offset()) {
        top = $(hashTag).offset().top
    }
    $('html, body').animate({scrollTop:top}, 'slow');                                                         
});

更新如下:http://bootply.com/62723