我有一個用圓圈創建 div 的函式。
現在它們都已創建并出現在頁面的開頭并按順序走得更遠。
接下來,我需要每個圓圈出現在隨機位置。我這樣做了,但只有一個問題。
當圓圈出現在頁面邊緣時,它會展開并出現滾動
我怎樣才能限制這一點,使圓圈不會離開頁面的邊緣?
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
currentTop = Math.floor(Math.random() * documentHeight) 1;
currentLeft = Math.floor(Math.random() * documentWidth) 1;
div.style.top = currentTop "px";
div.style.left = currentLeft "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i = 1;
createDiv(`circle${i}`)
}, oneSecond);
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
uj5u.com熱心網友回復:
我認為它來自兩件事:
- 獲得隨機位置時不補償圓的高度和寬度
- 20px的邊距也應該補償
在這里查看我的版本,如果您有一些問題,我會嘗試更清楚:)
var widthHeight = 40; // <-- circle width
var margin = 20; // <-- margin - is it necessary ?
var delta = widthHeight margin;
function createDiv(id, color) {
let div = document.createElement('div');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
div.setAttribute('class', id);
if (color === undefined) {
let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547'];
div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
else {
div.style.backgroundColor = color;
}
div.classList.add("circle");
div.classList.add("animation");
// Get the random positions minus the delta
currentTop = Math.floor(Math.random() * documentHeight) - delta;
currentLeft = Math.floor(Math.random() * documentWidth) - delta;
// Keep the positions between -20px and the current positions
var limitedTop = Math.max(margin * -1, currentTop);
var limitedLeft = Math.max(margin * -1, currentLeft);
div.style.top = limitedTop "px";
div.style.left = limitedLeft "px";
document.body.appendChild(div);
}
let i = 0;
const oneSecond = 1000;
setInterval(() => {
i = 1;
createDiv(`circle${i}`)
}, oneSecond);
.circle {
clip-path: circle(50%);
height: 40px;
width: 40px;
margin: 20px;
position: absolute;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/441177.html
標籤:javascript html jQuery css
