2012-05-04 76 views
1

我目前正在嘗試在我的網站(www.slatewerner.com)上製作自定義類燈箱功能。到目前爲止,我的方法是在點擊時將圖像包裹在一個div中,然後將其定位在內容流之外的絕對位置,並且具有半透明的灰色背景。除了着陸圖像/狀態外,我的所有圖像都通過AJAX加載。我面臨的問題是我無法使用「燈箱」功能訪問新加載的圖像。操縱文檔加載後動態加載的DOM元素

我的嘗試可以住在這裏找到:http://www.slatewerner.com/index_3.1

我怎樣才能使瀏覽器,jQuery的,或任何需要,請注意HESE新的圖像是在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

回答

1

使用.on而不是綁定你的點擊甚至處理器。這將確保even獲取當前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); 
}); 
+0

很好,這個工程。我調查過,但我顯然沒有得到它。謝謝。 – SL8