我正在尝试使用按钮上的 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/