Jquery平滑滚动鼠标滚轮效果

时间:2017-12-03 05:52:56

标签: javascript jquery asp.net twitter-bootstrap jquery-animate

当我的页面第一次加载时,我有一个全屏jumbotron。当用户使用鼠标滚轮向下滚动时,我想使用Jquery动画效果将导航栏(在jumbotron下面)带到页面顶部。 我已经有了一个可以实现这一目标的按钮,但我也想用鼠标滚轮来完成。

我怎样才能做到这一点? 谢谢

    <!-- Jumobtron-->
    <div class="jumbotron" style="height: 100vh;">
        <a href="#mainNavbar">
            <button type="button" class="btn" id="btnToNav">To Navbar</button>
        </a>
    </div>

    <!-- Navbar -->
    <nav class="navbar sticky-top" id="mainNavbar">
        <div class="container">
            <a asp-controller="Home" asp-action="Index" class="navbar-brand"> Brand </a>
        </div>
    </div>
</nav>

Jquery的:

$(document).ready(function() {
    $('#btnToNav').on('click', function(event) { 
        event.preventDefault();
        $('html, body').animate({
            scrollTop: $("#mainNavbar").offset().top
        }, 1000);
    });    
});

1 个答案:

答案 0 :(得分:0)

你可以使用
mousewheelDOMMouseScroll

如果你想在Firefox中运行该功能,你应该同时使用它们,因为Firefox没有mousewheel,但它们有DOMMouseScroll

$(document).ready(function() {
    $('#btnToNav').on('click', function(event){ 
      event.preventDefault();
      $('html, body').animate({
        scrollTop: $("#mainNavbar").offset().top
      }, 1000);
    });
    
    $('html, body').on('mousewheel', function(e){
      e.preventDefault();
      var delta = event.wheelDelta;
      if(delta < 0){
        // scroll from top to bottom
        $('html, body').animate({
          scrollTop: $("#brand").offset().top
        }, 1000);
      }else{
        // scroll from bottom to top
        $('html, body').animate({
          scrollTop: $("#btnToNav").offset().top
        }, 1000);
      }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Jumobtron-->
<div class="jumbotron" style="height: 100vh;">
  <a href="#mainNavbar">
    <button type="button" class="btn" id="btnToNav">To Navbar</button>
  </a>
</div>

    <!-- Navbar -->
<nav class="navbar sticky-top" id="mainNavbar">
  <div class="container">
    <a id="brand" asp-controller="Home" asp-action="Index" class="navbar-brand"> Brand </a>
  </div>
</nav>

相关问题