1

我想在每个列表元素后面生成三个随机彩色 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);
        }
});
4

4 回答 4

5

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

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

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

于 2012-08-20T20:40:45.643 回答
2

您在 javascript 中的 background-color 元素之后错过了一个冒号。jsFiddle

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

于 2012-08-20T20:40:06.723 回答
2

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

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

您只是忘记了函数中的冒号 ( :) 。background-colorsetAttribute()

于 2012-08-20T20:42:59.087 回答
1

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

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

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

于 2012-08-20T20:43:50.233 回答