需求:设置一个div网页滚动时,使其固定在头部,当页面滚动到距离头部300px时,隐藏该div,小于300px时,显示该div,.??那个显示和隐藏怎么做??
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> RunJS 演示代码 </title> <style> *{ margin:0; padding:0; } body{ height:3333px; } .head{ position:fixed; top:0px; width:100%; height:50px; text-align:center; line-height:50px; border:1px solid gray; background-color:#fd3; } </style> <script> var tt = 300; window.onscroll = function(){ var t = document.documentElement.scrollTop || document.body.scrollTop; if(t > tt && getStyle(dd,"display")!="none"){ dd.style.display="none"; }else if(t<tt&&getStyle(dd,"display")=="none"){ dd.style.display="block"; }else{ return false; } } var getStyle = function(dom,attr){ return dom.currentStyle ? dom.currentStyle[attr] : getComputedStyle(dom, false)[attr]; } </script> </head> <body> <div id="dd" class='head'> head </div> </body> </html> |
测试一下可以完美实现,需要的可以通过下面运行测试代码:
Tips:You can change the code before run.