Displaying images like Google Image Search

Does anybody know of a script that will let me diplay image results in the way that Google Image Search does (image grid view) with hover to enlarge and details? Something that I can just "plug-and-play" so to speak.


看看砌体http://masonry.desandro.com/


First, you need to put all images inside a container element:

<div class="parent">
    <img src="">
    <img src="">
    <img src="">
</div>

Then you need to make sure that the images are displayed in one line. This can be done by eg float: left . You should also set vertical-align to remove the small gap underneath each image:

img {
    float: left;
    vertical-align: top;
}

Finally you need some JavaScript to loop through all images and calculate the ideal rowHeight based on their dimensions. The only thing you need to tell this algorithm is the maximum row height that you want ( rowMaxHeight )

// Since we need to get the image width and height, this code should run after the images are loaded
var elContainer = document.querySelector('.parent');
var elItems = document.querySelector('.parent img');

var rowMaxHeight = 250; // maximum row height

var rowMaxWidth = elContainer.clientWidth;
var rowWidth = 0;
var rowRatio = 0;
var rowHeight = 0;
var rowFirstItem = 0;
var rowIsLast = false;
var itemWidth = 0;
var itemHeight = 0;

// Make grid
for (var i = 0; i < elItems.length; i++) {
    itemWidth = elItems[i].clientWidth;
    itemHeight = elItems[i].clientHeight;

    rowWidth += itemWidth;
    rowIsLast = i === elItems.length - 1;

    // Check if current item is last item in row
    if (rowWidth + rowGutterWidth >= gridWidth || rowIsLast) {
        rowRatio = Math.min(rowMaxWidth / rowWidth, 1);
        rowHeight = Math.floor(rowRatio * rowMaxHeight);

        // Now that we know the perfect row height, we just 
        // have to loop through all items in the row and set
        // width and height
        for (var x = rowFirstItem; x <= i; x++) {
            elItems[i].style.width = Math.floor(rowRatio * itemWidth * (rowMaxHeight/itemHeight)) + 'px';
            elItems[i].style.height = rowHeight + 'px';
        }

        // Reset row variables for next row
        rowWidth = 0;
        rowFirstItem = i + 1;
    }
}

Note that this code is not tested and a very simplified version of what this vanilla JavaScript plugin does: https://fld-grd.js.org


这可能是你正在寻找... http://www.gethifi.com/demos/jphotogrid

链接地址: http://www.djcxy.com/p/53526.html

上一篇: 如何开始使用Selenium 2?

下一篇: 显示Google图片搜索等图片