gpt4 book ai didi

javascript - 蛇形流体布局算法

转载 作者:技术小花猫 更新时间:2023-10-29 12:21:15 24 4
gpt4 key购买 nike

目标是生成如下所示的流畅布局。

enter image description here

到目前为止,我有一个工作函数 moveBox(lastBox, "east") 可以跟踪行和列索引。

function moveBox(box, where) {
switch (where) {
case "north":
lastTopOffset -= BOX_HEIGHT + BOX_MARGIN;
box.style.top = lastTopOffset + 'px';
box.style.left = lastLeftOffset + 'px';
rowIndex -= 1;
break;
// ...
}

我的 current code ,

(function () {
var i, lastBox,
MAX_DIVS = 72,
BOX_HEIGHT = 50,
BOX_WIDTH = 100,
BOX_MARGIN = 5,
field = document.getElementById('fieldPerimeter'),
fieldHeight = field.offsetHeight,
maxRows = Math.floor(fieldHeight / (BOX_HEIGHT + BOX_MARGIN)),
rowIndex = 0,
colIndex = 0,
lastLeftOffset = 0,
lastTopOffset = 0;

function moveBox(box, where) {
switch (where) {
case "north":
lastTopOffset -= BOX_HEIGHT + BOX_MARGIN;
box.style.top = lastTopOffset + 'px';
box.style.left = lastLeftOffset + 'px';
rowIndex -= 1;
break;

case "east":
lastLeftOffset += BOX_WIDTH + BOX_MARGIN;
box.style.top = lastTopOffset + 'px';
box.style.left = lastLeftOffset + 'px';
colIndex += 1;
break;

case "south":
lastTopOffset += BOX_HEIGHT + BOX_MARGIN;
box.style.top = lastTopOffset + 'px';
box.style.left = lastLeftOffset + 'px';
rowIndex += 1;
break;

default:
break;
}
}

for (i = 0; i < MAX_DIVS; i += 1) {
lastBox = document.createElement('div');
lastBox.className = 'box';
lastBox.innerHTML = i;
field.appendChild(lastBox);

//delete me
if( (i + 1) % 2 === 0 || (i + 1)% 3 === 0){
moveBox(lastBox, "east");
} else {
moveBox(lastBox, "south");
}
//delete me

// if(rowIndex < maxRows && rowIndex > 0){
// if (colIndex % 4 === 0){
// moveBox(lastBox, "south");
// } else if (colIndex % 2 === 0){
// moveBox(lastBox, "north");
// } else {
// moveBox(lastBox, "east");
// }
// }

}
})();

将 div 附加到容器,然后移动它。下面的代码显示了我尝试指定何时向北或向南移动的部分尝试。但我正在努力实现所需的布局。

 if      (colIndex % 4 === 0) { moveBox(lastBox, "south"); } 
else if (colIndex % 2 === 0) { moveBox(lastBox, "north"); }
else { moveBox(lastBox, "east"); }

最佳答案

enter image description here

这是工作 fiddle ,http://jsfiddle.net/efortis/zuY74/

请注意,我对 offsetHeight 进行了硬编码以便处理 fiddle ,并且还在顶部添加了一个 lastMove 变量。

  for (i = 0; i < MAX_DIVS; i += 1) {
lastBox = document.createElement('div');
lastBox.className = 'box';
lastBox.innerHTML = i;
field.appendChild(lastBox);

if (i === 0) {
rowIndex += 1;
} else {
if (colIndex % 4 === 0 && rowIndex < maxRows) {
moveBox(lastBox, "south");
lastMove = "south";
} else if (colIndex % 2 === 0 && rowIndex !== 1 && lastMove !== "south") {
moveBox(lastBox, "north");
lastMove = "north";
} else {
moveBox(lastBox, "east");
lastMove = "east";
}
}
}

关于javascript - 蛇形流体布局算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8030434/

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