您的位置:首页 > Web前端 > JavaScript

从JSON取数据实现图片瀑布流布局的数据动态加载

2014-03-29 22:02 981 查看
前段时间,做一个网站要用到图片的瀑布流布局。自己当时在网上找了一个仿花瓣网的瀑布流源码,不过它的数据是调用静态页面,繁杂,重用性差。我寻思着实现通过JSON调用数据。

先将效果呈上:http://www.i5wl.com/example/waterfall/

目录结构如下:

waterfall
——>css
——>style.css
——>js
——>jquery-1.9.1.js
——>jquery.infinitescroll.min.js
——>jquery.masonry.min.js
——>img
——>1.jpg , 2.jpg , 3.jpg --- 8.jpg
——>index.html
——>json.txt

先分析首页(index.html):

主要是infinitescroll函数的参数设置。

dataType参数设为“json”,即接受JSON格式的数据,如下:

dataType: 'json',

template参数,将从JSON传回的数据data传递给回调函数,回调函数要返回一个字符串,此字符串需要把data利用JS转换成瀑布流块的HTML格式。如下:

template: function(data) {
var more = '';
for(i = 0; i < data.pic.length; i++){
more = more + '<div class="pin wfc wft"><a class="img x" href="/pins/60411519/" target="_self"><img src="' + data.pic[i].url +'" width="192" height=' + data.pic[i].height + '><span style="display: none" class="stop"></span></a><p class="description">11111</p></div>';
}
return more;
},

瀑布流块的HTML格式,可以和template参数做一对比,如下:

<div class="pin wfc wft">
<a class="img x" href="/pins/60411519/" target="_self"><img src="img/1.jpg" width="192" height="301"><span style="display: none" class="stop"></span></a>
<p class="description">11111</p>
</div>

itemSelector参数,其内容即上面瀑布流块中的类.wfc。

nextSelector参数,设置瀑布流要加载的链接选择器,如下:

nextSelector: "#navigation a",

其对应的”#navigation a”块位于index.html的尾部,如下:

<div id="navigation"><a href="json.txt?page=1"></a></div>

链接中的“json.txt”即我们的JSON数据源,瀑布流会循环调用此JSON数据。

接下来分析json.txt:

json源里面每组数据有url和height项,即瀑布流中图片的地址和高度,在上面讲到的template参数中,调用形式为:data.pic.url 和 data.pic.height。

{
"pic":[
{
"url":"img/1.jpg",
"height":301
},
{
"url":"img/2.jpg",
"height":144
},
{
"url":"img/3.jpg",
"height":192
},
{
"url":"img/4.jpg",
"height":309
},
{
"url":"img/5.jpg",
"height":289
},
{
"url":"img/6.jpg",
"height":287
},
{
"url":"img/7.jpg",
"height":975
}
]
}


讲到这里,一个简单的JSON数据调用已经实现。下一步,我会研究如何通过数据库调用数据,来实现瀑布流布局的数据动态加载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: