我使用 html、css 和 js 制作了一個按鈕,這些按鈕在頁面上隨機出現。但我想要 body 標簽內的按鈕,并且它一直在退出。
HTML代碼:
<!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">
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>SReflex</title>
</head>
<body>
<button class="random">1 </button>
</body>
</html>
代碼:
*{
margin:0%;
padding:0%;
}
body{
height: 100vh;
width: 100vw;
position: fixed;
}
button.random {
/* looks of the button */
height: 3rem;
width: 3rem;
border: black;
border-style: solid;
border-radius: 50%;
display:block;
position:absolute;
}
JS代碼:
let temp= document.querySelector(".random");
temp.addEventListener("click",change);
function change(){
let posx = Math.floor(Math.random()*1000);
let posy = Math.floor(Math.random()*1000);
let posz = Math.floor(Math.random()*1000);
temp.style.left= posx "vw";
temp.style.top= posy "vh";
temp.style.right= posz "vw";
}
如何使按鈕不離開螢屏,我希望頁面不包含滾動條。
uj5u.com熱心網友回復:
這是一個簡單的方法,它適用于主體或包含的div,因為它與父級大小有關。查看代碼片段。
let temp= document.querySelector(".random");
temp.addEventListener("click",change);
let maxw = temp.parentElement.clientWidth - 50;
let maxh = temp.parentElement.clientHeight - 50;
function change(){
let posx = Math.floor(Math.random() * (maxw));
let posy = Math.floor(Math.random() * (maxh))
temp.style.left= posx "px";
temp.style.top= posy "px";
}
*{
margin:0%;
padding:0%;
}
body{
height: 100vh;
width: 100vw;
position: fixed;
}
button.random {
/* looks of the button */
height: 3rem;
width: 3rem;
border: black;
border-style: solid;
border-radius: 50%;
display:block;
position:absolute;
}
<!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">
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>SReflex</title>
</head>
<body>
<button class="random">1 </button>
</body>
</html>
該-50是為了確保它不跨的邊緣,你可以編輯,以滿足您的需求。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/401203.html
標籤:javascript html css
上一篇:如何為這些div設定影片?
