在页面滚动时隐藏元素,但是当页面变为静态时,元素再次出现

时间:2019-12-19 03:55:26

标签: javascript jquery

我在网站上添加了一个浮动操作按钮。我真的对JavaScript和jQuery一无所知。 我可以通过一种方法来使浮动操作按钮在窗口滚动时消失,而在窗口停止滚动时出现。

2 个答案:

答案 0 :(得分:1)

没有直接的滚动停止事件,但是这里有一个解决方法。 Event when user stops scrolling

只需添加一些调整,例如在滚动过程中隐藏按钮并显示按钮是否经过了几毫秒。

$.fn.scrollEnd = function(callback, timeout) {
  $(this).scroll(function() {
    // hide button
    $(".floatingBtn").hide();

    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback, timeout));
  });
};

$(window).scrollEnd(function() {
  // show button if scrolling stopped
  $(".floatingBtn").show();
}, 600);
.container {
  height: 1200px;
}

.floatingBtn {
  position: fixed;
  bottom: 12px;
  right: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <button class="floatingBtn">Hello World!</button>
</div>

答案 1 :(得分:1)

尝试以下代码。那应该工作。在以下代码中,将元素的ID替换为“ YOURID”。

command -v php
 $.fn.scrollStopped = function(callback) {
                      var that = this, $this = $(that);
                     $this.scroll(function(ev) {
                       clearTimeout($this.data('scrollTimeout'));
                       $this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
                     });
                   };
            $(window).on("scroll",function(e){ $("#YOURID").hide(); }).scrollStopped(function(ev){ 
                   $("#YOURID").show(); })