前端之masonry(图片瀑布流插件)

加载代码:

解释:很简单,就是把下载之后的脚本文件嵌入到你想使用瀑布流形式的页面中,注意文件的名称与路径,根据你自己的实际情况修改。

2,页面代码

1
2
3
4
5
6
7
8
<div id="masonry" class="container-fluid">
  <div class="box"><img src="http://jq22.com/images/1.jpg"></div>
  <div class="box"><img src="http://jq22.com/images/2.jpg"></div>
  <div class="box"><img src="http://jq22.com/images/3.jpg"></div>
  <div class="box"><img src="http://jq22.com/images/4.jpg"></div>
  <div class="box"><img src="http://jq22.com/images/5.jpg"></div>
  ...
</div>

解释:把每个小内容块放在一个拥有相关类的容器里,然后把所有的内容块放在一个大的容器里,这里我们把内容块图片放在一个拥有 .box 类的 <div> 标签里,然后把他们又使用带有 #masonry ID 的 <div> 里面,一会儿我们会用 #masonry ID 和 .box 类来触发使用瀑布流。

3,样式代码

1
2
3
4
5
6
7
8
9
10
11
.container-fluid {
  padding20px;
  }
.box {
  margin-bottom20px;
  floatleft;
  width220px;
  }
  .box img {
  max-width100%
}

解释:针对第二步的页面代码,我们需要添加一点样式,.box 类我们添加了浮动属性,还设置了他的宽度。

4,在页面中启用瀑布流形式的脚本代码

1
2
3
4
5
6
7
8
9
10
$(function() {
    var $container = $('#masonry');
    $container.imagesLoaded(function() {
        $container.masonry({
                itemSelector: '.box',
                gutter: 20,
                isAnimated: true,
            });
     });
});<br>

解释:这里我们首先定位想使用瀑布流的大容器是什么,这里就是带有 #masonry ID 的 <div> 标签,在 var $container = $('#masonry'); 这行代码中定义。然后我们还要说明瀑布流里的每个内容块容器上共同的类是什么,这里就是带有 .box 类的 <div> 标签,在itemSelector : '.box', 这行代码中定义。

gutter: 20, 这行代码定义了内容块之间的距离是 20 像素,isAnimated: true, 这行代码可以打开动画选项,也就是当改变窗口宽度的时候,每行显示的内容块的数量会有变化,这个变化会使用一种动画效果。

不居中显示的解决方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$(function() {
    var $objbox = $("#masonry");
    var gutter = 25;
    var centerFunc, $top0;
    $objbox.imagesLoaded(function() {
        $objbox.masonry({
            itemSelector: "#masonry > .box",
            gutter: gutter,
            isAnimated: true
        });
        centerFunc = function() {
            $top0 = $objbox.children("[style*='top: 0']");
            $objbox.css("left", ($objbox.width() - ($top0.width() * $top0.length + gutter * ($top0.length - 1))) / 2).parent().css("overflow", "hidden");
        };
        centerFunc();
    });
    var tur = true;
    $(window).resize(function() {
        if (tur) {
            setTimeout(function() {
                tur = true;
                centerFunc();
            },
            1000);
            tur = false;
        }
    });
});
原文地址:https://www.cnblogs.com/fu-yong/p/9223621.html