有很多方法。但让我看看这个特定网站是如何实现它的。
查看网页源代码,每张图片的HTML如下:
<div class="item" data-w="270" data-h="180">
<a href="/en/pine-forest-branch-road-conifer-463469/">
<img src="/static/uploads/photo/2014/09/27/13/36/pine-463469__180.jpg" class="preview_img" data-url="/static/uploads/photo/2014/09/27/13/36/pine-463469_640.jpg" data-width="492.307692308" data-height="327.692307692" alt="Pine, Forest, Branch, Road, Conifer" title="Pine, Forest, Branch, Road, Conifer">
<em>Pine, Forest, Branch, Road, Conifer</em>
</a>
</div>
在这里你可以看到,它们首先显示较小的图像,即/static/uploads/photo/2014/09/27/13/36/pine-463469__180.jpg,而较大的图像存储在<a>标签的data属性中,即data-url="/static/uploads/photo/2014/09/27/13/36/pine-463469_640.jpg"。这样可以先加载小图,节省带宽。
它的类preview_img 用于选择所有预览图像。您可以看到它的功能如下。他们使用的javascript文件是http://pixabay.com/static/js/base6.min.js,这是一个min文件。但是还是可以搜索preview_img找到代码制作效果:
var hover_timeout, no_preview=getCookie("no_preview");
$(document).on("mouseenter", ".preview_img", function(e) {
var o=$(this), i=e.pageX, n=e.pageY;
if(!no_preview || null != o.data("force-preview")) {
var r = o.attr("title");
r && (o.data("title",r), o.attr("title","")),
hover_timeout = setTimeout(function() {
var e=o.data("width"),
r=o.data("height"), a=r,
s=o.data("cut"),
c=o.data("title");
if(s&&(a+=s),!(e+30>ww||r+30>wh||e+30>wh||r+30>ww)) {
preview = $('<div class="open_preview_img" style="z-index:'+(max_zindex+10)+
'"><div style="position:relative;overflow:hidden;width:'+(e+2)+"px;height:"+(r+2)+
'px"><img style="width:'+e+"px;height:"+a+'px" src="'+o.attr("src")+'"><img style="width:'+e+'px" src="'+o.data("url")+'"></div>'+(c?"<em>"+c+"</em>":"")+"</div>").prependTo("body");
...
因此您可以看到他们将事件mouseenter 绑定到所有具有preview_img 类的图像。然后填充 HTML 代码和.prependTo("body")。并且可以看到图片的src属性为o.attr("src"),也就是大图的url。
这里的大部分代码是计算大图的位置/大小信息。根据您的应用程序,您可以自定义。