0

I am trying to get the dimensions of the viewport and then fill it squares so that they perfect cover the whole viewport. There must be a better way than my current code (below). Perhaps there is a way to find an easily divisible number for the denominator of this line var boxWidthHeight = wrapperArea / 30000;?

$(document).ready(function() {
    var wrapperWidth = $(window).width();
    var wrapperHeight = $(window).height();
    $('.wrapper').css('width', wrapperWidth);
    $('.wrapper').css('height', wrapperHeight);
    var wrapperArea = wrapperWidth * wrapperHeight;
    var boxWidthHeight = wrapperArea / 30000;
    var boxWidthHeight = parseInt(boxWidthHeight);
    var boxArea = boxWidthHeight * boxWidthHeight;
    var boxCount = wrapperArea / boxArea;
    for(var i = 0; i < boxCount; i++) {
        $('.wrapper').append('<div class="box"></div>');
    }
    $(".box").css({ width: boxWidthHeight, height: boxWidthHeight });
});
4

1 回答 1

1

http://jsfiddle.net/iambriansreed/nwPy5/

JavaScript

 $(function() {

    var box_size = 20,
        wrapper = $('.wrapper'),
        x = Math.round( wrapper.width()/box_size ) + 
        (wrapper.width()%box_size ? 1 : 0),
        y = Math.round( wrapper.height()/box_size ) + 
        (wrapper.height()%box_size ? 1 : 0),
        html = '';

    for(var i = 0; i <= x*y; i++)
        html += '<div class="box"></div>';

    wrapper.hide().html('<div class="inner">'+html+'</div>');

    $('.inner', wrapper ).css({'width' : x*box_size , 'height' : y*box_size , 'overflow': 'visible'});

    $('.box', wrapper ).css({
        'background': '#ccc',
        'width': box_size - 2,
        'height': box_size - 2,
        'border': '#fff solid 1px',
        'float':'left',
        'clear': 'none'
    });

    wrapper.show();

});​

HTML

<div class="wrapper"></div>​

CSS

.wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: #333;
    overflow: hidden;
}
于 2012-06-04T20:25:10.717 回答