[英]how to use intersection observer to show/hide an element
need to show nava
if wrapt
is not visible by scrolling the page如果通过滚动页面看不到wrapt
,则需要显示nava
and vice versa - hide the nava
if wrapt
is visible反之亦然 - 如果nava
可见,则隐藏wrapt
what is wrong with this JS code?这个 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>
Nothing wrong with the JS part, only the CSS. JS 部分没有问题,只有 CSS。 I've modified the nava
class so it will be visible when the page is scrolled down:我已经修改了 Nava 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.