DIV CSS 佈局教程網

跨窗體彈窗實戰:JS 鎖屏遮罩並彈出居中對話框
編輯:JavaScript綜合知識     

在 iframe 嵌套的頁面結構中,子窗體往往需要在父窗體上蓋一層半透明遮罩、再彈出一個居中的提示框,以實現類似 modal 的效果。下面這段代碼就通過操作父窗體的 document,動態創建遮罩層和對話框,並處理了定位與兼容性等細節。

代碼如下:

function sAlert() { var msgw,msgh,bordercolor; msgw=450; msgh=120; titleheight=25; bordercolor = "#104E8B"; var sWidth,sHeight; sWidth=screen.width; //取屏幕的寬和高 sHeight=screen.height; var bgObj=window.parent.document.createElement("div");//創建遮罩元素 bgObj.setAttribute('id','bgDiv'); bgObj.style.position="absolute"; bgObj.style.top="0"; bgObj.style.background="#cccccc"; bgObj.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75"; bgObj.style.opacity="0.6"; bgObj.style.filter = "alpha(opacity = 60)"; bgObj.style.left="0"; bgObj.style.width=sWidth + "px"; bgObj.style.height=sHeight +"px"; bgObj.style.zIndex = "10000"; window.parent.document.body.appendChild(bgObj); /*將遮罩加到父窗體上*/ var msgObj=window.parent.document.createElement("div"); msgObj.setAttribute("id","msgDiv"); msgObj.setAttribute("align","center"); msgObj.style.background="white"; msgObj.style.border="1px solid " + bordercolor; msgObj.style.position = "absolute"; msgObj.style.left = "50%"; msgObj.style.top = "50%"; msgObj.style.font="12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif"; msgObj.style.marginLeft = "-225px" ; msgObj.style.marginTop = -75+document.documentElement.scrollTop+"px"; msgObj.style.width = msgw + "px"; msgObj.style.height =msgh + "px"; msgObj.style.textAlign = "center"; msgObj.style.lineHeight ="25px"; msgObj.style.zIndex = "10001"; var title=window.parent.document.createElement("h4"); title.setAttribute("id","msgTitle"); title.setAttribute("align","center"); title.style.margin="0"; title.style.padding="3px"; title.style.background=bordercolor; title.style.border="1px solid " + bordercolor; title.style.height="18px"; title.style.font="12px Verdana, Geneva, Arial, Helvetica, sans-serif"; title.style.color="white"; title.style.cursor="pointer"; title.innerHTML ='hello'; window.parent.document.body.appendChild(msgObj); window.parent.document.getElementById("msgDiv").appendChild(title); }

幾個關鍵注意點

第一,子窗體操作父窗體時,一定要在 window 後加上 parent,明確作用於父層級。

第二,注意 IE 兼容性:調用 createElement 創建要加到父窗體上的元素時,也必須寫成 window.parent.*,因為在 IE 下加到父窗體的元素必須歸父窗體所有。

第三,用 setAttribute() 設置 class 屬性時 IE 並不支持,這種情況要改用直接賦值 element.className 的方式。

第四,設置透明度時,style.opacity 與 style.filter = "alpha(opacity = 60)" 這兩行是同一個屬性的兩種寫法,後者專門用來兼容 IE 的透明度設置。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved