使用jquery.masonry做瀑布流,图片重叠

JavaScript015

使用jquery.masonry做瀑布流,图片重叠,第1张

我们可以使用 jQuery 的 Masonry 插件来实现这种页面形式,下面介绍一下方法。

1,分别下载 jQuery 与 Masonry ,然后把他们都加载到页面中使用。

加载代码:

<script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script><script src="http://jq22.qiniudn.com/masonry-docs.min.js"></script>

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

2,页面代码

<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,样式代码

.container-fluid { padding: 20px }.box { margin-bottom: 20px float: left width: 220px } .box img { max-width: 100%}

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

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

$(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, 这行代码可以打开动画选项,也就是当改变窗口宽度的时候,每行显示的内容块的数量会有变化,这个变化会使用一种动画效果。

我的一个笨方法:

$(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 }})})

两种方法:

一、使用js瀑布流插件;

推荐masonry

二、使用css3样式

代码如下:

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8">

<title>布局</title>

<style>

ul{

/* 栏宽度 */

-webkit-column-width:160px

-moz-column-width:160px

-o-colum-width:160px

column-width:160px

/* 两栏之间的间距 */

-webkit-column-gap:1px

-moz-column-gap:1px

-o-column-gap:1px

column-gap:1px

}

li{

background:#0CF

border:#069 1px solid

display:inline-block

width:150px

margin:5px 0

}

</style>

</head>

<body>

<ul>

<li style="height:50px">1</li>

<li style="height:100px">2</li>

<li style="height:80px">3</li>

<li style="height:60px">4</li>

<li style="height:70px">5</li>

<li style="height:50px">6</li>

<li style="height:100px">7</li>

<li style="height:80px">8</li>

<li style="height:90px">9</li>

<li style="height:30px">10</li>

</ul>

</body>

</html>