-
案例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> body{ height: 2000px; background: linear-gradient(red, orange, yellow, pink, purple); } div{ /* 以body为参照物 */ position: absolute; /* 给其一个定位的位置 */ top: 300px; /* 左右都为0 那就是跟参照物等宽 */ left: 0; right: 0; background-color: deepskyblue; height: 50px; } </style> </head> <body> <div></div> <script> // 获取div var div_node = document.querySelector("div") document.onscroll = function(e){ // 向上滚动的位移 // document.body.scrollTop 不适配谷歌 var scroll_top = document.documentElement.scrollTop || document.body.scrollTop console.log(scroll_top) if(scroll_top >= 300){ // 设置成固定定位 固定在页面的顶端 div_node.style.position = "fixed" div_node.style.top = 0 }else{ div_node.style.position = "absolute" div_node.style.top = "300px" } } </script> </body> </html>
HTML——JS—滚动事件
最新推荐文章于 2024-02-10 09:00:00 发布