通過HTML+CSS+JavaScript實現滑鼠移動到頁面頂部導航欄出現,如果移出導航欄3秒又隱藏起來,而且不受滾動條影響(二)
阿新 • • 發佈:2022-01-18
通過HTML+CSS+JavaScript實現滑鼠移動到頁面頂部導航欄出現,如果移出導航欄3秒又隱藏起來,而且不受滾動條影響(二)
效果:預設一直隱藏導航欄,當滾動條滾到超過300px按鈕出現,點選回到頂部按鈕回到頂部,並隱藏按鈕,滑鼠移動到頂部導航欄出現,滑鼠移出導航欄後3秒後再次隱藏(導航欄和按鈕都是固定定位)
<!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>
本文來自部落格園,作者:永恆之月TEL,轉載請註明原文連結:https://www.cnblogs.com/akc4/p/15818335.html