gpt4 book ai didi

javascript - 根据可用空间堆叠 div

转载 作者:太空宇宙 更新时间:2023-11-04 06:52:25 25 4
gpt4 key购买 nike

我有一组 div,它们由 JavaScript 根据起始值和结束值生成、绝对定位并调整大小。

var posts = [
{
start: 50,
end: 200,
text: "Lorem ipsum"
},
{
start: 280,
end: 350,
text: "dolor"
},
{
start: 140,
end: 300,
text: "sit amet"
},
{
start: 440,
end: 590,
text: "consectetur"
},
{
start: 460,
end: 570,
text: "adipiscing"
},
{
start: 480,
end: 550,
text: "elit"
},
];

$.each(posts, function(i, post){
var obj = $("<div />");

obj.css({
left: post.start,
width: post.end - post.start
})
obj.text(post.text);

obj.appendTo("#timeline");
})
body {
font-family: Montserrat, Arial, sans-serif;
}

.timeline {
margin: 20px 0;
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
position: relative;
height: 60px;
}

.timeline div {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
height: 50px;
top: 5px;
background: darkblue;
color: #fff;
border-radius: 6px;
padding: 0 10px;
box-shadow: 0 0 0 2px #fff;
}


h1 {
font-size: 18px;
text-transform: uppercase;
color: #999;
font-weight: 400;
letter-spacing: 0.05em;
margin: 50px 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Current</h1>
<div id="timeline" class="timeline"></div>




<h1>Ideal</h1>
<!-- Height of the timeline adjusted to make room -->
<div class="timeline" style="height: 170px">
<div style="left: 50px; width: 150px;">Lorem ipsum</div>
<!-- This one not moved down because
there is still room for it in the
original position -->
<div style="left: 280px; width: 70px;">dolor</div>
<!-- Element moved down to
since it overlaps two previous ones -->
<div style="left: 140px; width: 160px; top: 60px;">sit amet</div>
<div style="left: 440px; width: 150px;">consectetur</div>
<!-- Element moved down -->
<div style="left: 460px; width: 110px; top: 60px;">adipiscing</div>
<!-- Element moved down even further -->
<div style="left: 480px; width: 70px; top: 115px;">elit</div>
</div>

但是,如果这些 div 中的两个或更多具有重叠的起始值和结束值,则生成的 div 也会重叠。理想情况下,我想计算哪些 div 会重叠,并添加一个 top 值,以便每个 div 都完全可见。 start 值较大的元素应向下移动。

我如何找出哪些元素重叠,以便将它们向下移动一两个等级?

最佳答案

这是一种有点幼稚的方法,它只是循环遍历所有帖子,并检查每个帖子与其他每个帖子。如果它发现它们在同一范围内,它会增加最高值。它只会比较具有相同最高值的帖子。

请注意,此运行时间为 O(n^2),这不是很好,但对于少量帖子,应该没问题。

function detectOverlaps(posts) {
for (let i=0; i<posts.length; i++) {
for (let j=0; j<posts.length; j++) {
if (i == j) continue;
var post1 = posts[i];
var post2 = posts[j];
if (post1.top != post2.top) continue;
if ((post1.start < post2.end && post1.start > post2.start) ||
(post1.end > post2.start && post1.end < post2.end)) {
var post = (post1.start>post2.start) ? post1 : post2;
if (!post.top) post.top = 0;
post.top += 60; // Change this by the pixel amount
}
}
}
return posts;
}

Here is the updated fiddle!

关于javascript - 根据可用空间堆叠 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730285/

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