图片墙的一种实现方式

来源:互联网 发布:直播刷人气软件 编辑:程序博客网 时间:2024/05/01 05:15

这里代码排版有点乱,欢迎大家看原文地址

原文地址:http://hi.baidu.com/niujiaming0819/item/92f279b3b8704a4dbb0e122f


最近浏览了一下百.度图.片,发现百.度图.片墙做的的确不错。自己也实现了一个桌面墙,在这里指说一下实现的方式吧。


其实,实现很简单,其原理如下:


1. 将页面分成5列,每一列的宽度自己可以定义


2. 计算每一列的高度

    2.1 计算高度的时候要注意,必须要在图片onload之后进行计算,应为图片资源必须加载后才能看到高度(如果你的图片高度是固定的,做图片墙就换别的方式实现吧,那样太容易了。)


3. 得到了每一列的高度后,选取那个最短的列,将图片append到这一列后面


下面是实现的关键代码:


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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//获取最短列,例子中共有5列
function get_min_height_column(){
    column_1_height = $('#column_1').outerHeight(true) + $('#column_1').offset().top;
    column_2_height = $('#column_2').outerHeight(true) + $('#column_2').offset().top;
    column_3_height = $('#column_3').outerHeight(true) + $('#column_3').offset().top;
    column_4_height = $('#column_4').outerHeight(true) + $('#column_4').offset().top;
    column_5_height = $('#column_5').outerHeight(true) + $('#column_5').offset().top;
       
    min_height = Math.min(column_1_height, column_2_height);
    min_height = Math.min(min_height, column_3_height);
    min_height = Math.min(min_height, column_4_height);
    min_height = Math.min(min_height, column_5_height);
       
    content = null;
    if(column_1_height == min_height) {
        content = $('#column_1');
    }
    else if(column_2_height == min_height) {
        content = $('#column_2');
    }
    else if(column_3_height == min_height) {
        content = $('#column_3');
    }
    else if(column_4_height == min_height) {
        content = $('#column_4');
    }
    else {
        content = $('#column_5');
    }
    return content;
}
       
//将result数组中的第index元素添加到图片墙中
function add_one_album(albums, index){
    if(index >= albums.length) return //如果index已经大于了albums的最大长度,直接返回
    min_column = get_min_height_column();//获取最短的列
           
    var album = $('#album').html();//获取存放图片的模板(我自己用div等包转了一下图片)
    album = album.replace('@src', albums[index]['a_cover_url']);
    album = album.replace('@cur_index', cur_index);
    album = album.replace('@a_id', albums[index]['a_id']);
    $(album).find('img')[0].onload = function(){ //注意这里,需要在图片加载完成后再显示下一张图片
        add_one_album(albums, index + 1);
    };
    min_column.append(album);//将这个图片添加到最短列中
    $('#cur_index_'+cur_index).show(); //显示这个图片
       
    cur_index = cur_index + 1;
}
//访问这个url会得到一个图片地址的json串
function add_more(url){
    $.getJSON(url, function(result){
        add_one_album(result, 0);
    });
}




用上面这种是先方式的好处是,我们可以加载不用高度的图片,图片墙做的就更加方便通用了。



再给大家推荐一个做法:


1. 在服务器端线计算好每个图片的高度


2. server下发图片时,同时下发图片的高度,这样客户端其实就可以直接获取最短列了,不用等到图片加载完成


3. 将图片依次append到最短列后



上面仅仅是我这个半吊子前端的看法,大家有什么想法可以随时拍砖 qq947847775


原文地址:http://hi.baidu.com/niujiaming0819/item/92f279b3b8704a4dbb0e122f

原创粉丝点击