首页 > 解决方案 > jQuery - 如何在滚动时淡出粘性按钮

问题描述

我有这个带有 CSS 类的按钮.comment-link。该按钮位于我的 wordpress 网站评论部分的顶部。当按钮进入视口时,我已将其设置为粘性。

当用户向上或向下滚动时,我希望它淡出到给定的透明度。当滚动停止时,按钮再次淡入。

我已经尝试过搜索但无法正常工作。

CSS:

.comment-link {
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 20px;
    float: right;
    font-size: 15px;
    display: inline-block;
    margin: -57px 0 0;
}

更新:

找到了这个脚本,但不知道如何在回调函数中实现淡入淡出。

// Setup isScrolling variable
var isScrolling;

// Listen for scroll events
window.addEventListener('scroll', function ( event ) {

    // Clear our timeout throughout the scroll
    window.clearTimeout( isScrolling );

    // Set a timeout to run after scrolling ends
    isScrolling = setTimeout(function() {

        // Run the callback
        console.log( 'Scrolling has stopped.' );

    }, 66);

}, false);

标签: jquery

解决方案


这应该是添加了淡入/淡出的代码,将不透明度更改为您想要的任何值,并且应该可以正常工作。(为了使按钮更加淡化而不是立即更改不透明度,添加transition: 0.3s all ease按钮的 css(comment-link))

var isScrolling;

// Listen for scroll events
window.addEventListener('scroll', function ( event ) {
    window.clearTimeout( isScrolling );
    let button = $('.comment-link');
		$(button).css('opacity', '0.3');
    isScrolling = setTimeout(function() {
				$(button).css('opacity', '1');
    }, 500);

}, false);
.comment-link {
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 20px;
    float: right;
    font-size: 15px;
    display: inline-block;
    margin: -57px 0 0;
    width: 50px;
    height: 25px;
}
.space{
  width: 100vw;
  height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="space">

</div>
<button class="comment-link">

</button>
<div class="space">

</div>


推荐阅读