我正在尝试创建一种类似于 Google Image 的行为,在该行为中单击网格中的其中一个图 block 会在该行的末尾插入一个元素。我有一个解决方案,但想知道是否有更高效的算法?
我有一个图 block 网格,所有列宽都向左浮动。我正在将单击的图 block 的 Y 坐标与下一组图 block 的 Y 坐标进行比较。如果它们的 Y 坐标与原始 Y 坐标不匹配,我就知道该图 block 属于下一行。
有没有更高效的算法?
$('.tile').click( function() {
var ele = $(this),
eleY = ele.position().top,
next = ele,
nextY = eleY;
while (eleY == nextY) {
next = $(next).next()[0];
nextY = $(next).position().top;
}
$(next).before('<div class="tile col-6">My New Tile</div>');
});
最佳答案
我无法证明这更有效,但这是我采用的方法。
$('.tile').click( function() {
showNew(this);
});
function showNew(tile)
{
var newtile = '<div class="tile tile--new col-6">My New Tile</div>';
if( $(tile).next('div').length )
{
var nextdiv = $(tile).next('div');
if(nextdiv.position().top > $(tile).position().top)
{
$(tile).after(newtile);
}
else
{
showNew( nextdiv );
}
}
else
{
$(tile).after(newtile);
}
}
关于javascript - 在下一行中插入新磁贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36075289/