<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1; user-scalable=no;">
<title>Document</title>
</head>
<script type="text/javascript" src="./jquery.min.js"></script>
<body>
<div>
<h5>我是头部内容<br>我是头部内容<br>我是头部内容<br>我是头部内容</h5>
<h4 id="road-tab">我是要吸顶的title</h4>
<div>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
<p>我是body</p>
</div>
</div>
</body>
</html>
<style>
*{
margin: 0;
padding: 0;
}
#road-tab {
width:100%;
background-color: #8bc34a;
padding: 15px 0;
}
.road-tab-fixed {
position: fixed;
top: 0;
}
</style>
<script type="text/javascript">
var fixedDom = $("#road-tab"),
tabclass = "road-tab-fixed";
var beforeElementScrollTop = 0;
var beforeOffsetTop = fixedDom[0].offsetTop; // 元素距离顶部的距离
//scroll节流
const throttle = (func,wait,mustRun) => {
var timeout,
startTime = new Date();
return function() {
var context = this,
args = arguments,
curTime = new Date()
clearTimeout(timeout)
// 如果达到了规定的触发时间间隔,触发 handler
if(curTime - startTime >= mustRun){
beforeElementScrollTop = document.body.scrollTop==0?document.documentElement.scrollTop:document.body.scrollTop;
// console.log("beforelementScrollTop:",beforeElementScrollTop);
func.apply(context,args);
startTime = curTime
// 没达到触发间隔,重新设定定时器
}else{
timeout = setTimeout(func, wait)
}
}
}
var winScroll = (e) => {
// 页面的滚动高度
var elementScrollTop=document.body.scrollTop==0?document.documentElement.scrollTop:document.body.scrollTop;
console.log("beforelementScrollTop:",beforeElementScrollTop);
console.log('elementScrollTop:',elementScrollTop);
if(beforeElementScrollTop - elementScrollTop <=0){//up
console.log('up');
if (beforeOffsetTop - elementScrollTop < 0){
console.log(111);
fixedDom.addClass("road-tab-fixed")
}
}else{
if (beforeOffsetTop - elementScrollTop >= 0){
console.log("down");
fixedDom.removeClass("road-tab-fixed")
}
}
};
$(window).off("scroll").on("scroll", throttle(winScroll,10,100));
</script>
转载于:https://my.oschina.net/shuaihong/blog/1835568