【问题标题】:Adding style to dynamically generated divs为动态生成的 div 添加样式
【发布时间】:2014-08-23 16:20:15
【问题描述】:

我正在处理this demo。为什么我无法为动态生成的 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
        });
    });

如你所见,我两种都试过了:

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

在循环内部并使用.each() 作为:

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

在循环之外,但显然他们没有做这项工作!

【问题讨论】:

标签: javascript jquery css


【解决方案1】:

因为您没有添加边距,所以您正在设置 topleft 位置,并且仅在元素没有静态位置时才有效

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

或者您实际上可以添加边距

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

作为旁注,您可以在创建元素时添加样式,第二个循环是不必要的

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

【讨论】:

  • 感谢 adeneo,但这也会导致一些问题。你能看看这里吗:jsfiddle.net/Behseini/k7mmybje/1
  • 它完全按预期工作,但可能与您预期的不同。你预计会发生什么?
  • 好吧,我只想在包装类中随机分离盒子。这就是为什么我尝试使用左右
  • 那么你必须在循环中获取随机值,现在你有 一个 随机数,并且你正在使用它所有框。
  • 因为边距总是为它们保持相同的大小,而且看起来它不是在迭代边距!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 2013-05-08
  • 2021-11-10
  • 2012-04-09
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
相关资源
最近更新 更多