创建一个按钮如何使这个按钮在网页中随机变换位置并且top小于500 left小于500
思路:利用Math.random()函数随机生成按钮位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
* {
padding: 0;
margin: 0;
}
#btn {
position: relative;
background-color: sandybrown;
padding: 5px 10px;
border: none;
border-radius: 20px;
color: whitesmoke;
}
</style>
<script>
function changePos () {
const btnDom = document.getElementById('btn')
const left = Math.random() * 500
const top = Math.random() * 500
btn.style.left = `${left}px`
btn.style.top = `${top}px`
}
window.onload = () => {
changePos()
}
</script>
</head>
<body>
<button id="btn">猜我在哪</button>
</body>
</html>
页面效果(刷新页面位置随机改变)
<div id="main">
<style>#button{position: absolute}</style>
<button id="button">按钮</button>
</div>
<script type="text/javascript">
var topVal = parseInt(Math.random() * 500)
var leftVal = parseInt(Math.random() * 500)
document.getElementById('button').setAttribute("style", `top: ${topVal}px;left: ${leftVal}px`);
</script>