【问题标题】:how to use intersection observer to show/hide an element如何使用交叉点观察器显示/隐藏元素
【发布时间】:2022-01-11 22:45:01
【问题描述】:

如果滚动页面看不到wrapt,则需要显示nava
反之亦然 - 如果 wrapt 可见,则隐藏 nava
这段 JS 代码有什么问题?

let io = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if(entry.isIntersecting){modify(entry.target);}
        else{revert(entry.target);}
    });
});

function modify(el){
  if(el.id == "wrapt"){$(nava).slideUp();}
}

function revert(el){
  if(el.id == "wrapt"){$(nava).slideDown();}
}

$(document).ready(function(){
    io.observe(document.querySelector('#wrapt'));
});
.nava{
display:none
height:25px;
background:orange;
position:relative;
z-index:9;
}
.wrapt{
height:54px;
background:lightblue;
}
.story{
height:200vh;
background:#ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='nava' id='nava'></div>
<div class='wrapt' id='wrapt'></div>
<div class='story'></div>

【问题讨论】:

    标签: javascript intersection-observer


    【解决方案1】:

    JS 部分没有问题,只有 CSS。 我已经修改了nava 类,所以当页面向下滚动时它会可见:

    .nava {
      display: none;
      height:25px;
      background: orange;
      position: fixed;
      width: 100%;
      z-index: 9;
      top: 0;
      left: 0;
    }
    

    let io = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          modify(entry.target);
        } else {
          revert(entry.target);
        }
      });
    });
    
    function modify(el) {
      if (el.id == "wrapt") {
        $(nava).slideUp();
      }
    }
    
    function revert(el) {
      if (el.id == "wrapt") {
        $(nava).slideDown();
      }
    }
    
    $(document).ready(function() {
      io.observe(document.querySelector('#wrapt'));
    });
    .nava {
      display: none;
      height:25px;
      background: orange;
      position: fixed;
      width: 100%;
      z-index: 9;
      top: 0;
      left: 0;
    }
    
    .wrapt {
      height: 54px;
      background: lightblue;
    }
    
    .story {
      height: 200vh;
      background: #ddd;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class='nava' id='nava'></div>
    <div class='wrapt' id='wrapt'></div>
    <div class='story'></div>

    【讨论】:

    • hmm...它有效,但nava 在整个身体之外。我尝试使用位置absolute - 不起作用。有什么建议吗?
    • 不确定想要的结果是什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多