console
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>吸顶容器</title>
<style>
body {
margin: 0px !important;
padding: 0;
box-sizing: border-box;
}
.cont{
margin: 0 10px;
}
.road-tab-fixed {
position: fixed;
top: 0;
left: 10px;
right: 10px;
}
.wrapper{
height: 50px;
width: 100%;
}
.top {
background: #c4f8b4;
height: 50px;
}
.list {
background: #ccc;
width: 100%;
}
.list li {
height: 50px;
border-bottom: 2px solid #f00;
}
.banner {
width: 100%;
background: #c19aff;
height: 150px;
}
</style>
</head>
<body>
<div class="cont">
<div class="banner">这是广告图</div>
<div class="wrapper"><div class="top" id="road-tab">菜单</div></div>
<div class="list">
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script>
var fixedDom = $("#road-tab"),
tabclass = "road-tab-fixed";
var beforeElementScrollTop = 0;
var beforeOffsetTop = fixedDom[0].offsetTop;
var throttle = function(fn, delay, mustRunDelay){
var timer = null;
var t_start;
return function(){
var context = this, args = arguments, t_curr = +new Date();
clearTimeout(timer);
if(!t_start){
t_start = t_curr;
}
if(t_curr - t_start >= mustRunDelay){
fn.apply(context, args);
t_start = t_curr;
}
else {
timer = setTimeout(function(){
fn.apply(context, args);
}, delay);
}
};
};
var winScroll = function(e) {
var elementScrollTop = getScrollTop()
if (beforeElementScrollTop - elementScrollTop <= 0) {
if (beforeOffsetTop - elementScrollTop < 0) {
fixedDom.addClass("road-tab-fixed")
}
} else {
if (beforeOffsetTop - elementScrollTop >= 0) {
fixedDom.removeClass("road-tab-fixed")
}
}
beforeElementScrollTop = getScrollTop()
};
var getScrollTop = function(){
return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
}
$(window).off("scroll").on("scroll",throttle(winScroll, 10, 100));
</script>
</body>
</html>