javascript居中的實作方法:先取得瀏覽器視窗;然後取得main的div元素;接著透過視窗寬高和div寬高計算位置;最後取得mcontent的div元素即可。
本文操作環境:windows7系統、javascript1.8.5版、Dell G3電腦。
具體問題:
javascript居中怎麼表示?
js讓div內容居中
var button=document.createElement("input"); button.setAttribute("type","button"); button.setAttribute("id","button1");
讓按鈕在div裡面是居中,要用js,不要html的
##實作方法:
text-align: center; line-height:100px; /*行间距和div宽度相同*/ } </style> <body> <div id="main"> <div id="content"> Sun </div> </div> <script type="text/javascript"> window.onload = function() { // 获取浏览器窗口 var windowScreen = document.documentElement; // 获取main的div元素 var main_div = document.getElementById("main"); // 通过窗口宽高和div宽高计算位置 var main_left = (windowScreen.clientWidth - main_div.clientWidth)/2 + "px"; var main_top = (windowScreen.clientHeight - main_div.clientHeight)/2 + "px"; // 位置赋值 main_div.style.left = main_left; main_div.style.top = main_top; // 获取mcontent的div元素 var content_div = document.getElementById("content"); var content_left = (main_div.clientWidth - content_div.clientWidth)/2 + "px"; var content_top = (main_div.clientHeight - content_div.clientHeight)/2 + "px"; content_div.style.left = content_left; content_div.style.top = content_top; } </script> </body>擴充資料Div上下居中程式碼
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <title>Div上下居中-www.51windows.Net</title> <head> <meta name="keywords" content="51windows.Net"> <meta http-equiv=content-type content="text/html; charset=gb2312"> </head> <body> <div style="position: absolute; top: 200; left: 0; width: 300; height: 200;border: 1 solid #C0C0C0;"> <div style="border: 1 solid red;position: absolute;top:expression((this.parentElement.offsetHeight-this.offsetHeight)/2);left:expression((this.parentElement.offsetWidth-this.offsetWidth)/2);">我站在中央了 center</div> </div> <div style="border: 1 solid #C0C0C0;"> <div style="border: 1 solid red;position: absolute;top:expression((this.parentElement.offsetHeight-this.offsetHeight)/2);left:expression((this.parentElement.offsetWidth-this.offsetWidth)/2);">我站在中央了 center</div> </div> </body> </html>【相關推薦:
javascript高階教學】#
以上是javascript居中怎麼表示的詳細內容。更多資訊請關注PHP中文網其他相關文章!