2017-12-03 206 views
0

当我的页面第一次加载时,我有一个全屏jumbotron。当用户使用鼠标滚轮向下滚动时,我想使用Jquery动画效果将导航栏(位于jumbotron下方)置于页面顶部。 我已经有一个按钮,可以实现这一点,但我想用鼠标滚轮来做。jquery平滑滚动鼠标滚轮效果

我该如何做到这一点? 谢谢

<!-- 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); 
    });  
}); 

回答

0

您可以使用
mousewheel OR DOMMouseScroll

如果你想运行在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>