這是一個完整實例,保存為 html 文件即可運行,兼容 Firefox、IE6、IE7、IE8、Chrome 等主流瀏覽器。
它實現的效果是:點擊按鈕彈出一個水平垂直居中的浮層,瀏覽器尺寸變化時浮層依然居中,點擊遮罩層可關閉浮層。涉及的知識點包括:用 CSS 控制 div 居中、用 JS 獲取瀏覽器寬高、以及 resize 事件的處理。
<style type="text/css">
.hidden{ display:none }
/* 評論浮動層 */
#smallLay{width:498px; height:100px;padding:4px 10px 10px;background-color:#FFFFFF;border:1px solid #05549d;color:#333333;line-height:24px;text-align:left;-webkit-box-shadow:5px 2px 6px #000;-moz-box-shadow:3px 3px 6px #555;}
</style>
<script type="text/javascript">
function showid(idname) {
var isIE = (document.all) ? true : false;
var isIE6 = isIE && ([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 6);
var newbox = document.getElementById(idname);
newbox.style.zIndex = "9999";
newbox.style.display = "block";
newbox.style.position = !isIE6 ? "fixed" : "absolute";
newbox.style.top = newbox.style.left = "50%";
newbox.style.marginTop = -newbox.offsetHeight / 2 + "px";
newbox.style.marginLeft = -newbox.offsetWidth / 2 + "px";
var jihualayer = document.createElement("div");
jihualayer.id = "jihualayer";
jihualayer.style.width = jihualayer.style.height = "100%";
jihualayer.style.position = !isIE6 ? "fixed" : "absolute";
jihualayer.style.top = jihualayer.style.left = 0;
jihualayer.style.backgroundColor = "#000";
jihualayer.style.zIndex = "9998";
jihualayer.style.opacity = "0.6";
document.body.appendChild(jihualayer);
var sel = document.getElementsByTagName("select");
for (var i = 0; i < sel.length; i++) {
sel[i].style.visibility = "hidden";
}
function jihualayer_iestyle() {
jihualayer.style.width = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth) + "px";
jihualayer.style.height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px";
}
function newbox_iestyle() {
newbox.style.marginTop = document.documentElement.scrollTop - newbox.offsetHeight / 2 + "px";
newbox.style.marginLeft = document.documentElement.scrollLeft - newbox.offsetWidth / 2 + "px";
}
if (isIE) { jihualayer.style.filter = "alpha(opacity=60)"; }
if (isIE6) {
jihualayer_iestyle();
newbox_iestyle();
window.attachEvent("onscroll", function () { newbox_iestyle(); });
window.attachEvent("onresize", jihualayer_iestyle);
}
jihualayer.onclick = function () {
newbox.style.display = "none";
jihualayer.style.display = "none";
for (var i = 0; i < sel.length; i++) { sel[i].style.visibility = "visible"; }
};
}
</script>
核心思路:非 IE6 用 position:fixed 天然實現居中與固定,並用負的 margin 抵消自身寬高的一半;IE6 則退回 absolute,再通過監聽 scroll、resize 事件動態計算位置。同時創建一個半透明遮罩層,並在 IE 下用 filter 兼容透明度,點擊遮罩即可關閉浮層。