2017-12-03 312 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>