我目前正试图在我的网站(www.slatewerner.com)上制作类似灯箱的自定义功能。到目前为止,我的方法是,在点击时,将图像包裹在div中,然后在内容流之外定位为绝对,并且具有半透明的灰色背景。除了着陆图像/状态之外,我的所有图像都是通过AJAX加载的。我面临的问题是我无法通过“灯箱”功能访问新加载的图像。
我的尝试可以在这里找到:http://www.slatewerner.com/index_3.1
如何制作浏览器,jQuery或其他任何需要,请注意这些新图像是否在DOM中?或者我如何重写我的功能,以便它对新加载的内容有效?
我的jQuery(只有灯箱部分):
$(document).ready(function(){
$('#content img').click(function(){
var img = this;
var width = img.clientWidth;
var height = img.clientHeight;
var imgWidth = -width/2;
var imgHeight = -height/2;
$(this).wrap('<div class="box"></div>');
$('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear');
$('.box').animate({'opacity':'1.00'}, 300, 'linear');
$('.backdrop, .box').css('display', 'block');
$('.box').css('margin-left', imgWidth);
$('.box').css('margin-top', imgHeight);
});
$('.close').click(function(){
close_box();
});
$('.backdrop').click(function(){
close_box();
});
});
function close_box()
{
$('.backdrop, .box').animate({'opacity':'0'}, 300, 'linear', function(){
$('.backdrop, .box').css('display', 'none');
});
}
我的CSS(仅限灯箱部分):
.backdrop {
position:absolute;
top:0px;
left:0px;
width:100%;
height:100%;
background:#000;
opacity: .0;
filter:alpha(opacity=0);
z-index:50;
display:none;
}
.box {
position:absolute;
top:50%;
left:50%;
background:#ffffff;
z-index:51;
padding:10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow:0px 0px 5px #444444;
-webkit-box-shadow:0px 0px 5px #444444;
box-shadow:0px 0px 5px #444444;
display:none;
}
.close {
float:right;
margin-right:6px;
cursor:pointer;
}
谢谢,
-Slate
答案 0 :(得分:1)
使用.on
来绑定点击偶数处理程序。这将确保均匀绑定当前在DOM中的元素以及稍后动态插入的元素。
$('#content').on('click', 'img', function(){
var img = this;
var width = img.clientWidth;
var height = img.clientHeight;
var imgWidth = -width/2;
var imgHeight = -height/2;
$(this).wrap('<div class="box"></div>');
$('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear');
$('.box').animate({'opacity':'1.00'}, 300, 'linear');
$('.backdrop, .box').css('display', 'block');
$('.box').css('margin-left', imgWidth);
$('.box').css('margin-top', imgHeight);
});