如何定位模块以显示像Pinterest?

时间:2016-06-17 09:30:09

标签: javascript jquery css plugins pinterest

我正在使用jQuery构建一个Pinterest类型的板插件,我很难弄清楚他们如何定位模块。

下面是每个元素在HTML中按照其第n个值放置的片段。但这不对,因为Pinterest会将元素放在最短列下面的下一行。就像这支钢笔http://codepen.io/nikhilkumar80/pen/oxpXVK,但我发现很难理解。

function modPosition() {
    $this.find(".pinterest-board__mod").each(function( modIndex ) {
        $(this).css({
            position: "absolute",
            left: columnWidth * (modIndex % settings.columns) + "%",
            width: columnWidth + "%"
        });
        // ..........
    });
}
modPosition();

这是我的CodePen链接,http://codepen.io/joshuawaheed/pen/beeJKq?editors=0010

我也很难弄清楚如何设置元素的顶部位置。

我可以做些什么来完成这项工作?我已经将它放在一个函数中,以便定位可以在文档大小调整时再次运行它,并且当用户单击过滤器选项以删除元素并从相应的数组中追加相应的模块时。该插件还设置为根据选项列值确定模块宽度。

提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以通过多种方式实施

我建议你两种方式

1)您可以使用其中一个js模块

你可以在那里阅读更多相关信息 https://designshack.net/articles/css/masonry/

http://www.wtfdiary.com/2012/08/6-amazing-jquery-plugins-to-design.html

2)您可以使用css规则(flexbox)

你可以在那里阅读更多相关信息

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

这两种方法都有正面和负面的特征

例如,所有版本的浏览器都不支持fleksboks

但JS更多地加载了处理器

答案 1 :(得分:0)

我已经开始工作了。我通过以下方式解决了这个问题:

  • 创建一个数组,其长度等于列数。
  • 将模块的高度值存储在数组的第一行中。
  • 循环浏览每个模块。
    • 将最小的数组值注入当前模块的css position top。
    • 使用包含最小值的数组项添加当前模块的高度。
    • 通过将100%除以数组中最小值的索引来设置位置左值。

以下是我编写的代码,您可以按照this link

查看和分叉
function modPosition() {

    var columnsHeight = [/* Length equal to column count */], // This will be recreated on window resize.
        columnCount = /* Column count value */;


    /* Set CSS position top and left. */
    function modCssTopLeft() {

        var columnIndex = 0;

        $this.find(".pinterest-board__mod").each(function( modIndex ) {

            var topPos = 0,
                leftPos = 0;

            if ( modIndex >= columnCount) {
                topPos = Math.min.apply( Math, columnsHeight ); // Get smallest value in array.
                leftPos = 100 * columnsHeight.indexOf(topPos) / columnCount; // Set left position based on column count.
                columnsHeight[columnsHeight.indexOf(topPos)] += $(this).outerHeight(); // Change arrays smallest value by adding it with current modules height.
            }
            else {
                leftPos = 100 * (modIndex++) / columnCount; // Positioning for the modules in the first row.
            }

            $(this).css({
                position: "absolute",
                top: topPos + "px",
                left: leftPos + "%"
            });

            $(this).closest(".pinterest-board__content").css({
                height: Math.max.apply( Math, columnsHeight ) // Set height to the modules parent container.
            });

        });
    }
    modCssTopLeft();
}
modPosition();

$(window).resize(function() {
    modPosition();
});