gpt4 book ai didi

javascript - 随机顶部/左侧定位

转载 作者:行者123 更新时间:2023-11-28 17:48:35 25 4
gpt4 key购买 nike

我有两个元素需要随机放置在容器中而不重叠。我的解决方案没有像我希望的那样工作。顶部/左侧的代码:

var toparray = [];
var leftarray = [];
var top;
var left;
for(var z = 0; z<termArray.length*2;z++){
toparray=toparray.sort(function(a,b){return a-b;});
leftarray=leftarray.sort(function(c,d){return c-d;});
toparray[z]=Math.floor((Math.random()*500)+50);
leftarray[z]=left = Math.floor((Math.random()*800)+50);
if(toparray[z]<=toparray[z-1]+50){
toparray[z]=Math.floor((Math.random()*500)+50);
}
if(leftarray[z]<=leftarray[z-1]+50){
leftarray[z]=Math.floor((Math.random()*800)+50);
}
}

我希望元素之间的距离至少为 50px。它们被调用并发送到一个新文档:

for(var i = 0; i<termArray.length;i++){ 
for(var q = 0; q<=1; q++){
if(q==0){
top = toparray[i];
left = leftarray[i];
}
else{
top = toparray[i+1];
left = leftarray[i+1];
}
docBody+='<span style="outline: 1px solid transparent; padding: 20px;top:'+top+'px;left:'+left+'px; cursor: pointer; max-width: 250px; display: table; position: absolute;" id="term'+i+'">'+termArray[i][q]+'</span>';
}
}

不幸的是,这是正在解决的问题: enter image description here

我的逻辑有什么问题吗?编辑:我的数组输出分别为 toparray 和 leftarray:

[147, 183, 198, 214, 238, 302, 407, 492, 545, 294]

[172, 233, 458, 576, 632, 639, 653, 755, 817, 582]

最佳答案

<!DOCTYPE html>
<html lang="en">
<head>
<title> Bla! </title>
<style type='text/css'>
div#divContainer { float:left; width:600px; height:600px; border-style:solid; }
div.child { position:absolute; width:40px; height:40px; border-style:solid; border-width:1px; }
</style>
<script type='text/javascript'>
var m_DivListPos = [];
function PositionOK(x,y) {
for (var i in m_DivListPos) {
var pos = m_DivListPos[i];
if (Math.abs(x-pos.x) < 50 ) return false;
if (Math.abs(y-pos.y) < 50 ) return false;
}
return true;
}

function AddObject() {
for (var i=0; i<100; i++) { // if not empty space, exit
var x = Math.floor((Math.random()*500)+50);
console.log (x);
var y = Math.floor((Math.random()*500)+50)
if (PositionOK(x,y)) {
m_DivListPos.push ( {'x':x, 'y':y});
var div = document.createElement('div');
div.className = 'child';
div.style.left = x + 'px';
div.style.top = y + 'px';
document.getElementById('divContainer').appendChild(div);
return ;
}
}
}
</script>
</head>
<body>
<button onclick='AddObject()'> Add object </button>
<div id='divContainer'>
</div>
</body>
</html>

关于javascript - 随机顶部/左侧定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22769974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com