CSS position下拉后元素悬浮
CSS 的position 有sticky和fixed,都可以实现悬浮效果,正常来讲下拉悬浮效果正常使用CSS就可以了。
CSS代码
.sticky { position: sticky; top: 0; }
但是由于父级的 overflow: hidden ,overflow: scroll, overflow: auto 会导致失效。所以我们可以考虑用JS来实现下拉后自动加入position:fixed
JS代码
<script>
var el = document.getElementById('xuanfu');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
window.addEventListener('scroll', function(){
if (document.documentElement.scrollTop > elTop){
el.style.position = 'fixed';
el.style.top = '60px';
}
else
{
el.style.position = 'static';
el.style.top = 'auto';
}
});
</script>