一、利用position的sticky属性
sticky
页面不动的情况下,它就像 position:relative;
而当页面滚动超出目标区域时,它表现的就像 position:fixed;,会固定在目标位置。
relative(相对定位)是指给元素设置相对于原本位置的定位,元素并不脱离文档流,因此元素原本的位置会被保留,其他的元素位置也不会受到影响。
而fixed:表示固定定位,与absolute定位类型类似,但它的相对移动的坐标并不是body,而是视图(屏幕内的网页窗口)本身
#sticky-nav { position: sticky; top: 0px; /**必须设置一个top值,否则不生效 */ width: 100%; height: 80px; background-color: yellowgreen;
}
但是浏览器兼容性不好
所以采取所以采取第二种方法
二、通过监听浏览器scroll事件,动态绑定class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> * { margin: 0; padding: 0 } html body { height: 100vh; width: 100% } h1 { height: 200px; position: relative; background-color: lightblue;
} h1:after { content: ''; position: absolute; top: 100px; left: 0; width: 100%; height: 2px; background-color: red;
} #sticky-nav {
/* position: sticky; */ top: 0px; /**必须设置一个top值,否则不生效 */ width: 100%; height: 80px; background-color: yellowgreen;
} .scroll-container { height: 600px; width: 100%; background-color: lightgrey;
} .fiexd { position: fixed; top: 0;
}
</style>
</head>
<body>
<h1>高200px;距顶部100px</h1>
<div id="sticky-nav">这是一个tab切换栏,给sticky定位top=100px</div>
<p class="scroll-container">发生滚动</p>
<p class="scroll-container" style="background:lightgoldenrodyellow;">发生滚动</p>
</body>
<script> window.onscroll = function(){ var scrollT = document.documentElement.scrollTop||document.body.scrollTop; var scrollH = document.documentElement.scrollHeight||document.body.scrollHeight; var clientH = document.documentElement.clientHeight||document.body.clientHeight console.log('scrollT:'+scrollT) console.log('scrollH:'+scrollH) console.log('clientH:'+clientH) if(scrollT>200){ console.log("滚轮已经大于200,置顶按钮出现"); document.getElementById('sticky-nav').classList.add('fiexd') //动态绑定class属性
}else { document.getElementById('sticky-nav').classList.remove('fiexd') //动态删除class属性
} } </script>
</html>