本文實例講述了JS實現自動固定頂部的懸浮菜單欄效果。分享給大家供大家參考。具體如下:
這是一款自動固定頂部的懸浮菜單欄代碼,不管你如何拉動滾動條,它會始終顯示在網頁的最頂部,用作網站的頂級導航或公告之類的比較合適吧。
運行效果截圖如下:
在線演示地址如下:
http://demo.VeVB.COm/js/2015/js-fix-top-float-menu-style-codes/
具體代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>自動固定頂部的懸浮菜單欄代碼</title><meta http-equiv="content-type" content="text/html;charset=gb2312"><style type="text/css">*{margin:0;padding:0;}ul,li{list-style:none;}#content{width:600px;margin:0 auto;border:1px solid #f00;}ul li.item{width:400px;text-align:center;margin:20px 100px;background:#00f;color:#fff;font-size:14px;font-weight:bold;height:100px;line-height:100px;}#float_banner{position:absolute;top:0;left:50%;width:900px;margin-left:-450px;height:30px;line-height:30px;text-align:center;background:#000;color:#fff;font-size:14px;font-weight:bold;z-index:2;}</style></head><body><div id="float_banner">這里是頂部的橫幅,隨著頁面滾動而浮動</div> <ul id="content"> <li class="item">第一塊內容</li> <li class="item">第二塊內容</li> <li class="item">第三塊內容</li> <li class="item">第四塊內容</li> <li class="item">第五塊內容</li> <li class="item">第六塊內容</li> <li class="item">第七塊內容</li> <li class="item">第八塊內容</li> <li class="item">第九塊內容</li> <li class="item">第十塊內容</li></ul><script language="javascript">var speed = 100;var scrollTop = null;var hold = 0;var float_banner;var pos = null;var timer = null;var moveHeight = null;float_banner = document.getElementById("float_banner");window.onscroll=scroll_ad;function scroll_ad(){ scrollTop = document.documentElement.scrollTop+document.body.scrollTop; pos = scrollTop - float_banner.offsetTop; pos = pos/10 moveHeight = pos>0?Math.ceil(pos):Math.floor(pos); if(moveHeight!=0){ float_banner.style.top = float_banner.offsetTop+moveHeight+"px"; setTimeout(scroll_ad,speed); }//alert(scrollTop);}</script></body></html>
希望本文所述對大家的JavaScript程序設計有所幫助。
新聞熱點
疑難解答