2012-03-23 41 views
2

我有一個jquery彈出腳本,並居中在屏幕上彈出的代碼是這樣的:jQuery的彈出找到真正的頂級

function centerPopup(){ 
    var windowWidth = document.documentElement.clientWidth; 
    var windowHeight = document.documentElement.clientHeight; 
    var popupHeight = $(".popupContent").height(); 
    var popupWidth = $(".popupContent").width(); 

    $(".popupContent").css({ 
    "position": "fixed", 
    "top": windowHeight/2-popupHeight/2, 
    "left": windowWidth/2-popupWidth/2 
    }); 
    } 

這工作,除非我需要激活一個div中的彈出標籤。它似乎進一步下降,有時離開頁面。我假設它認爲div標籤的頂部是頁面頂部。

我該如何解決這個問題並使其找到實際的主頁頂端?

+0

http://stackoverflow.com/questions/210717/using-jquery-to-center-a-div-on-the-screen – Kyle 2012-03-23 12:39:41

+0

你在quirksmode或使用IE6運行?這不應該發生在'position:fixed'上。你所描述的聽起來像'position:absolute'的預期行爲。或者,也許'centerPopup()'永遠不會被調用。你有沒有檢查你的調試器,以確保你的代碼被調用? – gilly3 2012-03-27 00:53:39

+0

檢查更新後的答案。 – 2012-03-27 13:13:10

回答

0

首先移動div外的彈出窗口。

function centerPopup(){ 
    var windowWidth = document.documentElement.clientWidth; 
    var windowHeight = document.documentElement.clientHeight; 
    var popupHeight = $(".popupContent").height(); 
    var popupWidth = $(".popupContent").width(); 

    $(".popupContent").css({ 
    "position": "fixed", 
    "top": windowHeight/2-popupHeight/2, 
    "left": windowWidth/2-popupWidth/2 
    }) 
    .prependTo('body'); //Put it at the top of the body dynamically 
    // .appendTo('body'); or the bottom 
    } 
+0

如果您滿足於您的居中過程並希望處理您的彈出窗口可能被另一個DIV包含的情況,這應該可以工作http://jsfiddle.net/bwGfy/5/ – 2012-03-27 12:10:19

0

您可以輕鬆,可靠地做到這一點,幾乎沒有JavaScript。只是一些CSS:

.popupContent { 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    height: 400px; 
    width: 500px; 
    margin-top: -200px; /* adjust upwards by half the height */ 
    margin-left: -250px; /* adjust leftwards by half the width */ 
} 

的想法是通過增加半人高的陰性切緣定位在頁面中心的元素的左上角,但後來轉向了起來,向左和寬度。

如果您在設計時不知道高度或寬度,請不要指定邊距。指定top: 50%left: 50%使用JavaScript在運行時設置頁邊距:

var popup = $(".popupContent"); 
popup.css({ 
    marginTop: popup.height()/2, 
    marginLeft: popup.width()/2 
}); 
2

你可以試試這個居中元素在瀏覽器中

$.fn.center = function() { 
    this.css("position","absolute"); 
    this.css("top", (($(window).height() - this.outerHeight())/2) + $(window).scrollTop() + "px"); 
    this.css("left", (($(window).width() - this.outerWidth())/2) + $(window).scrollLeft() + "px"); 
    return this; 
} 


$(".popupContent").center(); 

這裏是一個example

更新:example

+0

忽略實際問題。 OP會詢問關於何時將頁面內部的彈出窗口放在頁面內部的情況。如果該div具有已定義的位置,則彈出窗口的位置將與包含div的偏移量絕對。 http://jsfiddle.net/bwGfy/4/ – 2012-03-27 12:05:02

+0

試試這個http://jsfiddle.net/bwGfy/8/,現在開心嗎? – 2012-03-27 13:11:59

+0

老實說,沒有。首先,你最後一個小提琴甚至沒有證明自己解決了這個問題。箱子仍然位於其容器內。此外,您在父()選擇器上的嘗試僅上升一級。如果div在聲明位置的情況下嵌套在其他幾個div中,那麼您的代碼將變得毫無用處。這個想法是在屏幕上居中放置,即使它在另一個DIV中。出於某種原因,每個人都將其解釋爲只是集中在一般情況下,哪個OP不是很好,但它起作用,並且他的問題已被忽略 – 2012-03-27 14:32:33