追加子项删除样式

appendChild removes style

本文关键字:样式 删除 追加      更新时间:2023-09-26

我尝试使用appendChild函数来创建具有某些样式属性的新图像节点。使用它后,所有属性都将消失。图像应该随机放置在左侧div上,但是,实际上,它们被对齐成一行。

<html>
  <head>
    <title>Matching Game</title>
    <style>
        #rightSide {
            position: absolute;
            left: 700px;
            border-left: 1px solid black;
            width:700px; 
            height:700px;
        }
        #leftSide {
            width:700px; 
            height:700px;
            position: absolute;
        }
    </style>
</head>

<body onload="generateFaces()">
    <h1>Matching Game</h1>
    <p>Click on the extra smiling face on the left</p>
    <div id='leftSide'>
    </div>
    <div id='rightSide'>
    </div>
    <script>
        var numberOfFaces = 5;
        var theLeftSide = document.getElementById('leftSide');

        var generateFaces = function() {
            for(var i = 0; i < numberOfFaces; i++)
                {
                  var img = document.createElement('img');
                    img.src = 'smile.png';
                    img.style.top =  Math.floor(Math.random()*600);
                    img.style.left = Math.floor(Math.random()*600);
                    theLeftSide.appendChild(img);
                }
        }
    </script>
</body>

</html>

https://i.stack.imgur.com/fZaYA.png

Math.floor(Math.random()*600);将返回一个数字。除非值0,否则 CSS lefttop属性需要长度。长度有单位。

此外,您尚未将 position 属性从 static 更改为 ,因此 lefttop 属性将不起作用,因为它们仅适用于定位的元素。

这应该可以解决你的问题。

var img = document.createElement('img');
img.style.top =  Math.floor(Math.random()*600) + 'px';