onscroll方法
onscroll 事件在元素滚动条在滚动时触发。
css代码
.co{
position: fixed;
top: 0px;
}
.top_menu{
导航栏的样式
}
js代码
window.onload = function () { onscroll = function () { var t = document.documentElement.scrollTop || document.body.scrollTop;获取当前页面的滚动条纵坐标位置
if ( t >= 50 ) {
console.log( t )
document.getElementById( "top_menu" ).className = "top_menu co";
} else {
document.getElementById( "top_menu" ).className = "top_menu";
}
}
}
当滚动条运行大于 t 设定的值后
执行document.getElementById( "top_menu" ).className = "top_menu co";
给原有的导航栏在加上一个已经封装好的class
实现滚动条滚动时 导航栏固定
当 t 小于设定值时
执行document.getElementById( "top_menu" ).className = "top_menu";
恢复原来样式