欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用 HTML、CSS 和 JavaScript 实现页面顶部导航栏的动态显示和隐藏效果(二)

最编程 2024-08-08 09:42:04
...
<!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript_test</title> <style> body { margin: 0; padding: 0; height: 3000px; /*让滚动条出现*/ } .DW { display: flex; /*固定定位*/ justify-content: center; /*让文字水平居中*/ align-items: center; /*让文字垂直居中*/ width: 100%; height: 80px; background-color: green; /*背景颜色绿色*/ color: aliceblue; font-size: 2em; transition: top .5s linear; /*导航栏过渡出现和隐藏*/ position: fixed; /* 绝对定位,不管滚动条上下滚动都在相应的位置*/ top: -80px; /*隐藏导航栏*/ left: 0; } .goTop { width: 50px; height: 50px; background-color: aquamarine; font-size: 20px; text-align: center; line-height: 25px; color: azure; position: fixed; /*固定定位*/ bottom: 50px; right: 50px; display: none; /*隐藏按钮*/ } .fusu { position: fixed; /*固定定位*/ width: 100%; height: 10px; left: 0; top: 0; } </style> </head> <body> <div class="fusu divTop" id="divtop"></div> <div class="DW topdhl divdhl" id="dhl">导航栏</div> <buttion class="goTop" id="gotop">回到顶部</buttion> <script> //获取导航栏、按量、顶部div的元素 var topw=document.getElementById("dhl") var goTop=document.getElementById("gotop") var divTop=document.getElementById("divtop") //滚动滚动条触发事件 window.onscroll=function(){ //获取滚动条位置 var jhlheight=document.documentElement.scrollTop||document.body.scrollTop //判断滚动条位置 if(jhlheight>=300){ goTop.style.display="block" //显示按钮 }else{ goTop.style.display="none" //隐藏按钮 } } //点击按钮事件 goTop.onclick=function(){ window.scrollTo({ //设置滚动条位置 top:0, //回到顶部 behavior:"smooth" //平滑过渡 }) } //鼠标移入div后触发的事件 var ss=divTop.onmouseover=function(){ var tar=topw.style.top="0px" } //鼠标移入导航栏触发的事件 topw.onmouseover=function(){ var tar=topw.style.top="0px" } //鼠标移出导航栏后触发的事件 topw.onmouseout=function(){ //定时器函数 setTimeout(function(){ topw.style.top="-80px" },3000) } </script> </body> </html>