javascript - 如何在 JavaScript 上创建 div 并设置样式

标签 javascript html element

我正在尝试使用按钮上的 onclick 来调用完整函数,该函数应该创建一个具有以下属性的 div。但是,当我尝试运行它时,我没有看到任何输出显示。我已经尝试了很多事情,但目前不确定。任何帮助将不胜感激

<!DOCTYPE html>
<html>
    <button id ="button1" type="button" onclick="complete()">Run</button>
    <script>
        function complete(){
            var x= Math.floor(Math.random()*501)
            var y=Math.floor(Math.random()*501)
            var divx = document.createElement("div");
            divx.style.position = "fixed";
            divx.style.bottom = (150+x).toString();
            divx.style.right = (900+y).toString();
            divx.style.background="green";
            divx.style.width = "10px";
            divx.style.height = "10px";
            divx.style.border = "1px solid #000";
            document.body.appendChild(div);
        }
    </script>
</html>

最佳答案

document.body.appendChild(div); 应该是 document.body.appendChild(divx); 因为 div 未定义

<!DOCTYPE html>
<html>

<body>
  <button id="button1" type="button" onclick="complete()">Run</button>
  <script>
    function complete() {
      var x = Math.floor(Math.random() * 501)
      var y = Math.floor(Math.random() * 501)
      var divx = document.createElement("div");
      divx.style.position = "fixed";
      divx.style.bottom = (150 + x).toString();
      divx.style.right = (900 + y).toString();
      divx.style.background = "green";
      divx.style.width = "10px";
      divx.style.height = "10px";
      divx.style.border = "1px solid #000";
      document.body.appendChild(divx);
    }
  </script>
</body>

</html>

关于javascript - 如何在 JavaScript 上创建 div 并设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565252/

相关文章:

javascript - JS : looping function through checkbox array not counting properly

javascript - Photoshop 脚本获取控制位置

javascript - 如何关闭 node.js 中子进程的 stdio 管道?

javascript - 如何从元素中获取属性?

java - 如何在Jsoup中使用html()方法划分行

javascript - 如何在 Javascript 中获取表单文本字段数组的长度

javascript - 如何将鼠标悬停在超链接上 - Webdriver

javascript - 如何将多个 HTML 标签作为一个 javascript 变量

javascript - HighCharts 实体仪表图不显示刻度

javascript - 在文本字段后插入节点(表单)