开发者

jquery: calculate number of fitting divs and margin between them?

i have a bar in my footer called #elementbar. i want this elementbar to have 30px wide colored squares in it. And those sqaures should have a margin between them around 10px.

what i wanna do now is calculate exactly the amount of elements that would fit in the width of the body. and i want to calculate the margin between them so the elements have exactly the same margin from start to end. now i have just manually set the margin in css but in this case very first element has a slightly different distance to the browseredge than the last one.

is there mathematical solution to calculate the fitting elements as well as the appropriate margin between them (the margin should always be around 5px to 10px)

#elementbar {
    overflow:hidden;
    height:15px;
    bottom:0px;
    position:fixed;
    text-align:center开发者_StackOverflow社区;
}

#elementbar .element {
    width: 30px;
    height: 15px;
    float:left;
    /*margin:0px 5px 0px 5px;*/
}

#elementbar .element {
    margin:0px;
}

jquery:

function elementbar() {
    var bw = Math.round($('body').width());
    var num = Math.round(bw / 30); //one element is 30px wide
    for (var i=0; i<num; i++) {
        $("#elementbar").append("<div class='element'></div>");
    }
}
elementbar();

later i want also to call the function on resize so that whenever you resize the browser the appropriate number of elements gets appended to the elementbar.

any ideas? thank you


<div class="bar"></div>
<div class="debug"></div>

var bw = $('.bar').width();
var num = Math.floor(bw/40); // Assume 30px width + 10px margin
var margin = Math.floor((bw - num*30)/(num-1));

for (i=0; i<num; i++) {
  $(".bar").append("<span class='block'>&nbsp;</span>");
}       
$('.block').css({ marginRight: margin + 'px'});
$('.block:last').css({ marginRight: '0px'});

$(".debug")
    .append("Width: " + bw +
            ", marginRight: " + margin +
            ", number: " + num);

See it in action: jsfiddle.net/s4MGT/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜