是否解决了你说的问题?
<!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>Document</title>
<style>
html,
body {
height: 100%;
margin: 0;
}
#not {
position: fixed;
top: 0;
left: 0;
border: 0;
background-color: aqua;
width: 50px;
height: 30px;
line-height: 30px;
text-align: center;
}
</style>
</head>
<body>
<button id="not">随机</button>
<script>
const btn = document.getElementById('not');
const maxTop = document.body.clientHeight;
const maxLeft = document.body.clientWidth;
function getRandomPos() {
const randomTop = Math.floor(Math.random() * (maxTop - 50));
const randomLeft = Math.floor(Math.random() * (maxLeft - 30));
return {
randomLeft,
randomTop
}
}
btn.onmouseenter = () => {
const { randomLeft, randomTop } = getRandomPos();
btn.style.top = randomTop + 'px';
btn.style.left = randomLeft + 'px';
};
</script>
</body>
</html>