2011-06-27 31 views
-2

任何人都可以告訴我這段代碼有什麼問題嗎?我試圖垂直和水平居中我的網頁,但這不起作用!這不是我的中心。用jQuery水平和垂直居中設置網頁

<html> 
<head> 
    <title>String Functions</title> 
    <script type="text/javascript" src="js/jquery-1.5.2.min.js"></script> 
    <script type="text/javascript"> 
    jQuery.fn.center = function() { 
    this.css("position", "absolute"); 
    this.css("top", ($(document).height() - this.height())/2 + $(document).scrollTop() + "px"); 
    this.css("left", ($(document).width() - this.width())/2 + $(document).scrollLeft() + "px"); 
    return this; 
    }; 

    $("#d1").center(); 
    </script>  
</head> 

<body> 

<div id="d1" style="background-color:red;width:100px; height: 100px;"></div>  

</body> 

+2

你看到了什麼問題?我沒有看到一個...我改變了窗口來記錄。 http://jsfiddle.net/euALd/ – CrazyDart

+0

你好,這根本就不是我的中心。上面的代碼就是我所擁有的。 – davidz

+0

它也適用於我。你使用的是什麼瀏覽器?控制檯是否會拋出錯誤? – Ivan

回答

1

試試這個。

jQuery.fn.center = function() { 
    this.css({ 
     "position" : "absolute", 
     "top" : "50%", 
     "left" : "50%", 
     "margin-left" : (this.width()/2) * -1, 
     "margin-top" : (this.width()/2) * -1 
    }); 
}; 

非常可靠的方式居中絕對定位的元素是從左側或頂部的位置設定爲50%,然後將其裕度至約一半的物體的寬度或高度。