Looping using position absolute to form 9 boxes

大兔子大兔子 提交于 2020-01-25 20:37:10

问题


1 2 3
4 5 6
7 8 9

I want to achieve above boxes position using absolute positioning and looping in js. But I'm stuck at starting a second line.

http://jsfiddle.net/k554x7vs/

var left = 0;
for (var i = 1; i <= 10; i++) {

    $('<div class="box" id=box' + i + '></div>').appendTo('#holder');

    if (i == 3) {

        //2nd line and so on..
        left = 0;
        $('#box' + i).css({
            'top': 70
        })



    }


    $('#box' + i).css({
        'left': left
    });

    left += 60;
}

There's a reason why I don't use float left.


回答1:


You need to increment top also

var left = 0,
    top = 0;
for (var i = 1; i <= 10; i++) {
    $('<div class="box" id=box' + i + '></div>').appendTo('#holder');
    $('#box' + i).css({
        'left': left,
        top: top
    });
    left += 60;
    if (i % 3 == 0) {//need to increment top also need to use the modulus operator since you want to reset/increment after each 3rd element
        left = 0;
        top += 70;
    }
}

Demo: Fiddle




回答2:


The solution is pretty simple. It's a bit hard to explain what I changed, but this works:

var left = 0;
for (var i = 0; i <= 10; i++) {

    $('<div class="box" id=box' + i + '></div>').appendTo('#holder');

    if (i % 3 == 0) {

        //2nd line and so on..
        left = 0;



    }
        $('#box' + i).css({
            top: (i - i % 3) / 3 * 70
        })


    $('#box' + i).css({
        'left': left
    });

    left += 60;
}



回答3:


Try

var arr = [1,2,3,4,5,6,7,8,9]
, n = -1;

$.map(arr, function(val, key) {
    var box = $(".box"),
    height = box.height() + 20,
    width = box.width() + 20,
    len = box.length;
    $("<div>", {
        "class":"box",
        "id":"box" + key,
        "css": {
            "left": key < 3 
                    ? (len * width)
                    : box.eq(++n).css("left"),

            "top": key < 3 
                   ? 0 
                   : key < 6
                     ? height 
                     : (2 * height)
        }
    }).appendTo("#holder")
});

http://jsfiddle.net/k554x7vs/6/



来源:https://stackoverflow.com/questions/29137152/looping-using-position-absolute-to-form-9-boxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!