如何在javascript中模拟float:top

How to simulate a float:top in javascript

本文关键字:float top 模拟 javascript      更新时间:2023-09-26

我有一个很大的项目列表,我想要浮动,但理想情况下,我希望它们从上到下、从左到右堆叠。向左浮动将它们从左到右、从上到下堆叠。

如何在本地代码或jQuery中模拟javascript中的css float:top属性?

示例代码:

<style>
*{margin:0;padding:0;}
ul {
    height:80px;
    width:350px;
    margin:10px;
    padding:0;
    outline:1px solid;
}
li{
    float:left;
    list-style:none;
    margin:0;
    padding:3px 5px;
}
</style>
<ul>
    <li>1679</li>
    <li>1682</li>
    <li>1732</li>
    <li>1761</li>
    <li>1773</li>
    <li>1781</li>
    <li>1788</li>
    <li>1791</li>
    <li>1797</li>
    <li>1799</li>
    <li>1832</li>
    <li>1861</li>
    <li>1873</li>
    <li>1879</li>
    <li>1881</li>
    <li>1882</li>
    <li>1888</li>
    <li>1891</li>
    <li>1897</li>
    <li>1899</li>
    <li>1932</li>
    <li>1932</li>
    <li>1961</li>
    <li>1961</li>
</ul>

这里也有类似的问题,但它似乎在寻找更多的CSS解决方案,而不是基于js的解决方案。此外,这个问题是布局修复的一个更具体的实现。

不要重新发明轮子!

http://masonry.desandro.com/

jQuery Masonry所做的正是您所描述的。而且它非常容易实现。不过,您可能需要稍微更改标记。

您需要查看css3多列。http://caniuse.com/#search=column

https://developer.mozilla.org/en/CSS3_Columns

这对我来说很好,在窗口调整大小/更改列表时调用

function layout(oList) {
    var column = 0,
        top = 0,
        bottomMargin=20,
        width = 300;
        $(oList).each(function () {
            if (top !=0 && $(this).height() + top > $(window).height()) {
                top = 0;
                column += 1;
            }
            $(this).css("top", top + "px");
            $(this).css("left", (column * width) + "px");
            top = top + $(this).height() + bottomMargin;
        }
    );
}

使用javascript可以制作智能列。这里有一个jsfiddle,它将适应每个li的不同高度和宽度,以确保列的平滑:http://jsfiddle.net/rgthree/hAeQ2/

var list, currentColLeft, currentColTop, nextColWidth;
currentColLeft = currentColTop = nextColWidth = 0;
list = $('ul#list');
$('ul > li').each(function(i, el){
    var h, w;
    h = $(el).outerHeight();
    w = $(el).outerWidth();
    if(currentColLeft + w > nextColWidth){
        nextColWidth = currentColLeft + w;
    }
    if(currentColTop + h > list.innerHeight()){
        currentColTop = 0;
        currentColLeft = nextColWidth;
        nextColWidth = 0;
    }
    $(el).css({'float':'none','position':'absolute','top':currentColTop,'left':currentColLeft});
    currentColTop += h;
});

因此,您可以对所有li进行循环,并将它们定位在您想要的位置。。

var origionalX = 100;
var origionalY = 200;
var columns = 10;
$("li").each(function(i){
  var x = origionalX+parseInt(i/columns)*$(this).width();
  var y = origionalY+(i%columns)*$(this).height();
  $(this).css({position : "absolute", left : x, top : y});
});

希望这会有所帮助。如果你想要更具体的东西,请随时发表评论,我会看看我是否能提供帮助。:]