【问题标题】:Is there a way to hide element on scroll and show when the user stops scrolling?有没有办法在滚动时隐藏元素并在用户停止滚动时显示?
【发布时间】:2019-09-12 02:00:47
【问题描述】:

我有一个滚动指示器按钮,当用户滚动时将 X 翻译出屏幕,并在用户向上滚动时显示回来。我希望按钮在用户停止滚动时出现/返回,而不是在他们向上滚动时显示/返回。

我尝试切换类,但它的行为不正确。

jQuery:

var prev = 0;
var $window = $(window);

$window.on('scroll', function(){
    var scrollTop = $window.scrollTop();
    scrollButton.toggleClass('hidden', scrollTop > prev);
    prev = scrollTop;
});

CSS:

.hidden {
   transform: translateX(250%);
 }

【问题讨论】:

标签: jquery html css


【解决方案1】:

您可以通过将Timeout 用作threshold 来实现。

例如:

var timer;
$(document).scroll(function(){

  if(timer != "undefined"){
    clearTimeout(timer);
  }
  
  $('p').hide();
  timer = setTimeout(function(){
    
    $('p').show();

  },250)//Threshold is 100ms

});
<style>

body{height:1000px;width:100%;}
div{width:100%;height:150px;overflow:hidden;}
p{background-color:black;color:white;width:100px;margin:50px auto;padding:20px;}  

</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Hide on scroll</p>
</div>

注意:确保您要隐藏的部分包含在里面 具有overflow:hidden; 属性的 div 容器,也使用固定的 高度,因为每次切换该部分时,文档都会 自动滚动,这将再次触发事件(去抖动)。

我希望这行得通!

【讨论】:

  • 这也称为debouncing - 实际上您可能想要更小的超时,但作为示例显示。
猜你喜欢
  • 2022-10-04
  • 1970-01-01
  • 2020-02-13
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多