【问题标题】:How can I show an element after scrolling and hide when entering another element?如何在滚动后显示元素并在输入另一个元素时隐藏?
【发布时间】:2021-04-23 22:49:28
【问题描述】:

我想在滚动后显示一个 DIV,例如向下 800 像素。 为此,我使用great snippet from here

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});

效果很好。但现在我想添加另一个步骤。 如果我滚动到站点的.footer,我想再次隐藏 DIV,直到我离开页脚。

我想我可以从上面的答案中更改另一个 sn-p:

$('.footer').each(function () {
    var y = $(document).scrollTop();
    var t = $(this).parent().offset().top;
    if (y > t) {
        $('.bottomMenu').fadeIn();
    } else {
        $('.bottomMenu').fadeOut();
    }
});

不幸的是,我无法弄清楚。

【问题讨论】:

  • 您的第二个 sn-p 只会在页面加载时被调用。这是你的意图吗?
  • 不,如果我输入 .footer 并在离开它之后应该调用它:-/
  • 我会尝试使用交叉点观察器。

标签: javascript html jquery css scroll


【解决方案1】:

使用交叉点观察器,您可以在页脚可见时触发fadeOut

let isFooterVisible = false;
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800 && isFooterVisible === false) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});
function isIntoView(entries, obs){
  entries.forEach(entry => {
     if (entry.target.id === 'fter'){
       if (entry.isIntersecting === true){
         isFooterVisible = true;
         $('.bottomMenu').fadeOut();
       }
       else{
         isFooterVisible = false;
       }
     } 
  });
}
let options = {
  root: null,
  rootMargin: '0px',
  threshold: 0
};
let observer = new IntersectionObserver(isIntoView, options);
let target = $('#fter')[0];
observer.observe(target);
body{
  height: 1700px;
  width: 100%;
  position: absolute;
}
.bottomMenu{
  position: fixed;
  top: 100px;
  display: none;
  background-color: #f07;
}
#fter{
  position: absolute;
  width: 100%;
  height: 100px;
  background-color: #0f7;
  bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bottomMenu">
  Here is the menu
</div>
<footer id="fter">
  Here is the footer
</footer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2013-03-26
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多