2012-12-06 75 views
0

我想將一個具有一定高度和一定寬度的div盒放置到具有一定高度和一定寬度的屏幕中心。將數學公式放置在中心的算術算法

檢測JavaScript的寬度和高度。我試圖成爲一名更好的程序員,數學和編程並不總是我最好的特質。我知道我需要做一些部門和百分比修復,但需要一個指針:

<script type="text/javascript"> 

var w=document.width; 
var h=document.height; 

var img_w=200; 
var img_h=300; 

var css=; 

/* 

Example 

w=600; 
h=400; 

img_w=200; 
img h=300; 


therefore css will be 

position:absolute; 
top:150px; 
left:100px; 
right:100px; 
bottom:100px; 

see my image. 

*/ 

document.writeln(css); 
</script> 

enter image description here

所以基本上,無論img_wimg_h是,這個盒子應該在中心與邊際位置。

回答

2

請讓我建議一種替代方法。

CSS不是一種程序性的聲明性語言。讓瀏覽器爲你做數學運算並使用margin: auto。我明白這不是你正在尋找的東西,但CSS只是它。

查看http://jsfiddle.net/th43T/舉例。

1

你正在尋找的公式如下:

left = (width - img_width)/2 
top = (height - img_height)/2 

PS:在你的榜樣,你倒hw

0

我首先想到的數學(如其他指出的)

數學是:(總寬度 - 圖片寬度)/ 2,同去的高度

但是,爲什麼是頂部150像素和底部在你的例子100px?

+0

實際的圖像比例會改變,因此我上面的圖像居中。 – TheBlackBenzKid

0
Block css:{ 
    left: 50%; 
    top: 50%; 
} 

JS (useing jQuery): { 
    block.css({ 
     'margin-left': '-' + (block.outerWidth()/2), // margin-left: -1/2 of block width 
     'margin-top': '-' + (block.outerHeight()/2), // margin-top: -1/2 of block height 
    }) 
} 
0

如果您需要在窗口大小調整期間保持居中,您還需要檢查窗口大小調整事件。

我創造了這個的jsfiddle:http://jsfiddle.net/ekRff/1/

的javascript:

function updateBoxPosition($box) { 
    var window_width = $(window).width(); 
    var window_height = $(window).height(); 
    var left_pos = (window_width - $box.width())/2; 
    var top_pos = (window_height - $box.height())/2; 

    $box.css('left', left_pos); 
    $box.css('top', top_pos); 
} 

$(function() { 
    var $box = $("#box"); 
    var window_width = 0; 
    var window_height = 0; 

    var resizeTimer; 
    $(window).on('resize', function() { 
     clearTimeout(resizeTimer); 
     resizeTimer = setTimeout(function() { 
      updateBoxPosition($box); 
     }, 25); 
    }); 

    updateBoxPosition($box);   
});​ 

頂部函數處理的定位和定位綁定onload事件過程中完成。它的劑量需要jQuery,但我的確推薦用於這種情況,因爲瀏覽器處理窗口寬度的方式有很多不同。

爲resize事件添加的計時器是爲了提高性能,resize事件在調整大小的過程中被相當頻繁地觸發。