【问题标题】:Spawn different, random colored DIVs for each list element为每个列表元素生成不同的、随机颜色的 DIV
【发布时间】:2012-08-20 20:34:38
【问题描述】:

我想在每个列表元素后面生成三个随机颜色的 div 框。我从这个开始,但是它不起作用 - DIV 似乎不可见:(

http://jsfiddle.net/dgweu/1/

非常感谢您的帮助!

HTML

<div id="wrapper">
    <ul>
        <li>li1</li>
        <li>li2</li>
        <li>li3</li>
    </ul>
</div>​

JS

$("li").each(function(){
    var randomColor = "#"+Math.floor(Math.random()*16777215).toString(16);
        for (var i = 0; i < 3; i++) {
            stripe = document.createElement('div');
            stripe.setAttribute('style', 'width:100px; height:3px; background-color' + randomColor);  
            wrapper = document.getElementById("wrapper");
            wrapper.appendChild(stripe);
        }
});

【问题讨论】:

    标签: javascript jquery html css dom


    【解决方案1】:

    div 不可见,因为您的 CSS 中存在语法错误。在background-color 之后,您缺少:

    要让 div 出现在 lis 后面,您可以将 div 绝对定位,lis 相对定位。

    看看这个DEMO。我也整理了你的 JS。

    【讨论】:

    • 您删除了 for 语句,这对于期望的结果是必不可少的(“每个列表元素后面的三个随机颜色的 div 框”)。另请注意,随机颜色生成可能会产生无效的十六进制值。
    • 将 randomColor 生成移到 for 循环中,它会立即生效。
    • 太好了,正是我需要的,谢谢!与此同时,我想出了另一个解决方案,但它很混乱而且很糟糕......
    【解决方案2】:

    您在 javascript 中的 background-color 元素后遗漏了一个冒号。 jsFiddle

    stripe.setAttribute('style', 'width:100px; height:3px; background-color:' + randomColor);

    【讨论】:

      【解决方案3】:

      您的想法是正确的,但是您的 JavaScript 中有一个简单的语法错误。

      stripe.setAttribute('style', 'width:100px; height:3px; background-color:' + randomColor); 
      

      您只是忘记了 setAttribute() 函数中 background-color 后面的冒号 (:)。

      【讨论】:

        【解决方案4】:

        你的背景颜色后面缺少一个冒号

        另一件事,你说你想在每个列表元素后面插入彩色 div。你的脚本只会在最后添加元素

        我相信这就是你想要的
        http://jsfiddle.net/dgweu/4/
        经常使用jquery,非常方便。 jQuery 的 insertbefore 方法让一切变得更简单 你创建一个元素,查询它,然后在每个 li 元素之前插入它

        【讨论】:

          猜你喜欢
          • 2015-05-25
          • 1970-01-01
          • 2017-09-11
          • 1970-01-01
          • 2021-04-17
          • 2016-12-16
          • 2014-04-14
          • 1970-01-01
          • 2019-05-09
          相关资源
          最近更新 更多