<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width' />
<style>
html,
body {
margin: 0
padding: 0
height: 1000px
}
</style>
<script>
window.addEventListener('load', function () {
window.onscroll = function () {
// 页面向下卷积的距离
var scroll = document.documentElement.scrollTop || document.body.scrollTop
console.log(scroll)
}
}, false)
</script>
</head>
<body>
</body>
</html>
百度知道对于代码的支持度很低,书写不太友好。这段就是模拟监听页面滚动距离的代码,很简单。
利用scroll 事件来监听。
当用户滚动指定的元素时,会发生 scroll 事件。
scroll 事件适用于所有可滚动的元素和 window 对象(浏览器窗口)。
scroll() 方法触发 scroll 事件,或规定当发生 scroll 事件时运行的函数。
<script>window.onscroll=function(){//变量t就是滚动条滚动时,到顶部的距离var t =document.documentElement.scrollTop||document.body.scrollTop
var left =document.getElementById("left")if( t >=100) { //当拖动到距离顶部100px处时,左边导航固定,不随滚动条滚动
left.style.position="fixed"left.style.top="0"
}else{
//恢复正常left.style.position="absolute" left.style.top="100px"}}</script>