导航条置顶
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li class="top"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
* {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
.top {
height: 100px;
background-color: red;
}
li {
width: 100%;
height: 100px;
background-color: pink;
margin-bottom: 20px;
}
var oUl=document.getElementsByTagName('ul')[0];
var otop = document.getElementsByClassName('top')[0];
var navh = otop.offsetTop;
//2.添加滚动事件,如果滚动的距离大于等于pingjia的div到body的距离,就可以一直停在顶部
window.onscroll = function () {
var top1 = document.documentElement.scrollTop || document.body.scrollTop;
if (top1 >= navh) {
otop.style.position = 'fixed';
otop.style.top = '0';
} else {
otop.style.position = 'relative';
}
}
效果图