javascript图像位置

标签 javascript html css dom

我试图将微笑图像放在左侧 div 的随机位置。但图像不是随机出现的,而是连续显示图像。为什么会这样?

<html>
    <head>
    <h1>Matching Game</h1>
    <p>Click on the extra smiling face on the left</p>
    <div id= "leftSide"></div>
    <div id = "rightSide"></div>
    <style>
        img1 {position:absolute}
        div {position:absolute; width:500px;height: 500px}
        #rightSide {left:500px;border-left: 1px solid black}
    </style>
         <script>
            var numberOfFaces =5,i;
            var theLeftSide = document.getElementById("leftSide");


            function generateFaces()
            {
                for( i=0;i<numberOfFaces;i++)
                {
                var img1 =document.createElement("img");
                img1.src = "smile.png";
                var topran = Math.random() * 400;
                var topran = Math.floor(topran);
                var leftran = Math.random() *400;
                var leftran = Math.floor(leftran);
                img1.style.top = topran + "px"; 
                img1.style.left = leftran + "px";
                theLeftSide.appendChild(img1);
                }
            }

        </script>
    </head>
    <body onload = "generateFaces()">

    </body>
</html>

最佳答案

您不能在 CSS 中使用 img1 {position:absolute} 来设置微笑图像的样式。将您的 CSS 更改为 .smile {position:absolute}(类选择器)并在 img1 上设置类 smile

var img1 =document.createElement("img");
img1.src = "smile.png";
img1.className = "smile";

关于javascript图像位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895150/

相关文章:

jquery - 背景不申请位置固定div的父元素

javascript - Mongoose:尝试在集合中的项目数组中执行 forEach

javascript - 遍历 ES6 类的方法和属性

javascript - 在 mousemove 上旋转对象以面对鼠标指针

jquery - 使用 jquery 显示/隐藏一级 div

javascript - 如何在新浏览器中隐藏或更改鼠标光标?

css - Mailchimp 'Style Declaration Block' 不工作

html - li 标签不应显示多个 li 列表标签中的任何内容

javascript - 将两个列表转换为 json

php - jQuery 变量值未获取