2012-12-06 29 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事件在调整大小的过程中被相当频繁地触发。