jsBin demo
你可以用一种非常简单的方式做到这一点:
<img alt="" src="images/thumb.jpg" data-gallery='[
"images/1.jpg",
"images/2.jpg",
"images/3.jpg"
]'>
我们在缩略图上点击:
- 打开我们的响应式图库叠加层(在 CSS 中将
background-size 设置为 cover)
-
JSON.parsethumbnail data 属性获取图片数组
- 统计图片数量
- 如果有超过 1 张图片 >> 显示 prev/next
span 按钮
- 将一些
click() 函数分配给我们的SPAN 按钮>> 以更改背景图像。
- 如果在图库外部单击,则将其隐藏。
让我们先做一些样式:
#gal{
display: none; /* jQ will make visible */
position: fixed;
z-index: 99999;
top:0; left:0; right:0; bottom:0;
margin: 50px;
background: no-repeat #444 none 50% / cover;
box-shadow: 0 5px 10px -3px rgba(0,0,0,0.9), 0 0 0 5000px rgba(0,0,0,0.6);
}
#gal:after{
pointer-events: none;
content : "×";
position: absolute;
right: -30px;
top: -40px;
color: #fff;
font-size: 3em;
}
#gal > span{
display: none; /* jQ will make visible if >1 image*/
cursor: pointer;
background: rgba(255,255,255,0.7);
position: absolute;
top: 50%;
width: 50px;
height: 50px;
margin-top: -25px;
}
#gal > span:nth-child(1){ left:0; }
#gal > span:nth-child(2){ right:0; }
...最后应用我们的 jQuery 图库逻辑:
var $call = $("[data-gallery]"),
$gal = $('<div/>',{id:"gal", html:"<span/><span/>"}),
$btn = $gal.find("span"), img, n, c, hov=0;
$('body').prepend($gal);
// SHOW GALLERY || CHANGE IMAGE
function galleryAnim() {
$gal.stop().slideDown(300).css({backgroundImage: "url("+img[c]+")"});
}
// THUMBNAIL CLICK
$call.click(function() {
img = JSON.parse(this.dataset.gallery); // Creates an Array of images
n = img.length; // Get total images
c = 0; // Reset Counter
$btn[n>1?"show":"hide"](); // show||hide prev/next btns
galleryAnim();
});
// PREV NEXT BUTTONS
$btn.click(function() {
c = ($(this).index()>0 ? ++c : --c)<0 ? n-1 : c%n; // Loop Counter
galleryAnim();
});
// HIDE GALLERY IF EXOCLICK
$gal.hover(function() { hov ^= 1; });
$(document).mousedown(function() {
if (!hov) $gal.slideUp(300);
});
如果您不想等待每张新图片在点击“上一个/下一个”后加载,要预加载所有图片,只需在n = img.length; 之后添加此代码:
for(var i=0; i<n; i++){
var _temp = new Image();
_temp.src = img[i];
}