如何在平滑滚动栏中使用滚动动画

时间:2020-03-26 09:55:58

标签: jquery

我正在使用平滑的滚动条https://github.com/idiotWu/smooth-scrollbar#demo,该滚动条使滚动动画(如下)停止工作。

我想了解原因,以及是否可以同时使用两者? 代码:

编辑:我将代码包含在JS中,以初始化注释掉的平滑滚动条以演示滚动动画

$(function() {

var header = $("header");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();    
        if ($(window).scrollTop() > 20) {
            header.addClass('scroll');
        } else {
            header.removeClass('scroll');
    }
   
   
    });
});    
body {
	margin:0;
	padding:0;
	font-size: 1rem; 
	font-family: sans-serif;

}

#scroll {
  width: 100%;
  height: 150vh;
  overflow: auto;
}


header {
    width: 100%;
    padding: 4rem 10rem 1.5rem;
    font-size:1.5rem;
    z-index: 9997;
    mix-blend-mode: difference;
    opacity: 1;
    transition: all ease-in 0.3s;
    position: fixed;
    text-transform: uppercase;
    margin: 0 auto;
}




header.scroll {
    padding: 1.5rem 10rem 1.5rem;
}
<!-- CSS -->
<link rel="stylesheet" href="https://unpkg.com/smooth-scrollbar@latest/dist/smooth-scrollbar.css">



<body>
<main id="scroll" data-scrollbar>

<header>Test</header>


</main>
</body>

<!-- JS -->
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>  
        <!-- script src="https://unpkg.com/smooth-scrollbar@latest/dist/smooth-scrollbar.js"></script>
        
        <script> 

            Scrollbar.initAll();
            Scrollbar.detachStyle();

        </script -->

var header = $("header");
$(window).scroll(function() {
    var scroll = $(window).scrollTop();    
    if ($(window).scrollTop() > 20) {
        header.addClass('scroll');
    } else {
        header.removeClass('scroll');
}

1 个答案:

答案 0 :(得分:1)

使用$(window).scrollTop()代替Scrollbar.scrollIntoView(element,options),类似:

scrollbar.scrollIntoView(document.querySelector('#anchor'), {
  offsetLeft: 34,
  offsetBottom: 12,
  alignToTop: false,
  onlyScrollIfNeeded: true,
});

更多官方文档:https://github.com/idiotWu/smooth-scrollbar/blob/develop/docs/api.md#scrollbarscrollintoview