本文實例講述了JQuery獲取可視區尺寸和文檔尺寸及制作懸浮菜單。分享給大家供大家參考,具體如下:
獲取可視區尺寸和文檔尺寸
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $(function () { console.log('可視區的寬度:'+$(window).width()); console.log('可視區的高度:'+$(window).height()); console.log('文檔的高度:'+$(document).height()); console.log('文檔的寬度:'+$(document).width()); }) </script></head><body> <p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /></body></html>
可視區和文檔的寬度是一樣的,可視區和文檔的高度不一樣。
console.log('可視區的寬度:'+$(window).width());console.log('可視區的高度:'+$(window).height());console.log('文檔的高度:'+$(document).height());console.log('文檔的寬度:'+$(document).width());
scrollLeft和scrollTop
置頂菜單
懸停菜單:
往下拉動滾動條的時候,如果菜單超出瀏覽器的可視區了,就懸停在瀏覽器上部
實現方法:
得到scrolltop的值,如果菜單出去了,就把菜單絕對定位在上部
position:'fixed', 固定定位
left:'50%', 和marginLeft一起使用,使菜單居中
top:0,
marginLeft:-480
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> body{ margin: 0; } .banner{ width: 960px; height: 200px; background-color: cyan; margin: 0 auto; } .menu{ width: 960px; height: 100px; background-color: gold; margin: 0 auto; text-align: center; line-height: 80px; } p{ text-align: center; color: red; } </style> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> $(function () { $menu=$('.menu'); $(window).scroll(function () { var iNum=$(document).scrollTop(); // document.title=iNum; if(iNum>200){ $menu.css({ position:'fixed', left:'50%', top:0, marginLeft:-480 }) } else { $menu.css({ position:'static', marginLeft:'auto' }) } }) }) </script></head><body> <div class="banner"></div> <div class="menu">菜單</div> <p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /><p>文檔內容</p> <br /> <br /> <br /> <br /></body></html>
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具 http://tools.VeVB.COm/code/HtmlJsRun 測試上述代碼運行效果。
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery常見事件用法與技巧總結》、《jQuery常用插件及用法總結》、《jQuery操作json數據技巧匯總》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答