我正在尝试创建一个按钮,单击它会在文档上创建一个具有所述高度和宽度的div。通过给div.style.left和div.style.top提供一个随机数,div将具有随机位置。它不起作用,你能让我知道为什么吗?我真的很感激。谢谢。
<html>
<head>
<title></title>
</head>
<body>
<button id = "button" onclick = "addMonster()">add monster</button>
<div id = "square">
</div>
<style>
#square {
width: 100px;
height: 100px;
background-color: white;
border: 2px solid black;
font-size:20px;
color: black;
position:absolute;
left: 50px;
top: 80px;
}
* {
box-sizing: border-box;
}
body, html {
margin: 0;
padding: 0;
}
</style>
<script>
var monster = {
height: 0,
width: 0,
top: 0,
left: 0
};
function addMonster() {
monster.height = 100;
monster.width = 100;
monster.left = Math.floor((Math.random() * 100) + 1);
monster.top = Math.floor((Math.random() * 100) + 1);
var div = document.createElement('div');
document.body.appendChild(div);
div.style.width = monster.width + "px";
div.style.height = monster.height + "px";
div.style.left = monster.left + "px";
div.style.top = monster.top + "px";
div.style.backgroundColor = "red";
div.style.border = 2px solid red;
div.innerHTML = "hello";
};
</script>
</body>
</html>
答案 0 :(得分:0)
您的代码中存在错误,导致无法定义addMonster()
方法。
用引号括起2px solid red
,事情应按预期工作。
我建议你学习在浏览器中使用开发者控制台,这可以帮助你轻松查明这样的错误。祝你好运!
答案 1 :(得分:0)
此行导致您的代码中断。
div.style.border = 2px solid red;
应该是
div.style.border = "2px solid red";
P.S:始终检查开发人员控制台是否有错误,未定义变量等问题,可以使用它轻松调试意外标识符。
var monster = {
height: 0,
width: 0,
top: 0,
left: 0
};
function addMonster() {
monster.height = 100;
monster.width = 100;
monster.left = Math.floor((Math.random() * 100) + 1);
monster.top = Math.floor((Math.random() * 100) + 1);
var div = document.createElement('div');
document.body.appendChild(div);
div.style.width = monster.width + "px";
div.style.height = monster.height + "px";
div.style.left = monster.left + "px";
div.style.top = monster.top + "px";
div.style.backgroundColor = "red";
div.style.border = "2px solid red";
div.innerHTML = "hello";
};
&#13;
#square {
width: 100px;
height: 100px;
background-color: white;
border: 2px solid black;
font-size: 20px;
color: black;
position: absolute;
left: 50px;
top: 80px;
}
* {
box-sizing: border-box;
}
body,
html {
margin: 0;
padding: 0;
}
&#13;
<html>
<head>
<title></title>
</head>
<body>
<button id="button" onclick="addMonster()">add monster</button>
<div id="square">
</div>
</body>
</html>
&#13;