简体   繁体   English

为动态生成的 div 添加样式

[英]Adding style to dynamically generated divs

I am working on this demo .我正在做这个演示 Why am I not able to add margin to dynamically generated divs?为什么我不能为动态生成的 div 添加边距?

jQuery(function () {
    var rnd1 = Math.ceil(Math.random() * 450);
    var rnd2 = Math.ceil(Math.random() * 450);
    for (var i = 0; i < 6; i++) {
        $('.wrapper').append('<div class="box"></div>');
        //        $('.box').css({"left": rnd1,"top": rnd2});
    }
    $(".box").each(function () {
        $(this).css({
            "left": rnd1,
            "top": rnd2
        });
    });

As you can see I tried both:如您所见,我尝试了以下两种方法:

$('.box').css({"left": rnd1,"top": rnd2});

inside the loop and using .each() as:在循环内并使用.each()作为:

 $(".box").each(function () {
        $(this).css({
            "left": rnd1,
            "top": rnd2
        });
    });

out of the loop but apparently they are not doing the job!出圈,但显然他们没有做这项工作!

Because you're not adding margin, you're setting the top and left position, and that only works if the element doesn't have a static position因为您没有添加边距,所以您正在设置topleft位置,并且仅当元素没有静态位置时才有效

$(this).css({"left": rnd1,"top": rnd2, position: 'relative'});

or you could actually add margin instead或者你实际上可以添加保证金

$(this).css({"margin-left": rnd1, "margin-top": rnd2});

As a sidenote, you can add the styles when you're creating the elements, the second loop is uneccessary作为旁注,您可以在创建元素时添加样式,第二个循环是不必要的

for (var i = 0; i < 6; i++) {
    $('.wrapper').append(
        $('<div />', {
            'class' : 'box',
            css : {
                marginLeft : rnd1,
                marginTop  : rnd2
            }
        })
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM