显示Google图片搜索等图片
有没有人知道一个脚本会让我以Google图片搜索的方式显示图片结果(图片网格视图)并悬停放大和细节?我可以直接即插即用的东西。
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.
首先,你需要将所有图像放入容器元素:
First, you need to put all images inside a container element:
<div class="parent">
<img src="">
<img src="">
<img src="">
</div>
然后你需要确保图像显示在一行中。这可以通过例如 float:left
。您还应该设置 vertical-align
以删除每个图像下方的小间隙:
Then you need to make sure that the images are displayed in one line. This can be done by e.g. float: left
. You should also set vertical-align
to remove the small gap underneath each image:
img {
float: left;
vertical-align: top;
}
最后你需要一些JavaScript循环遍历所有图像并计算理想的rowHeight在他们的尺寸上。您需要告诉此算法的唯一方法是您想要的最大行高( rowMaxHeight
)
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;
}
}
请注意,此代码未经过测试且非常简化这个vanilla JavaScript插件的版本: https://fld-grd.js.org
Note that this code is not tested and a very simplified version of what this vanilla JavaScript plugin does: https://fld-grd.js.org