2013-06-04 41 views
0

我在「li」中有一個「a」標籤,並且在懸停的「li」上懸掛幾個圖像到同一個「a」標籤中,我不得不使用內聯樣式在所有這些img元素上,但問題是當我第一次懸停在「li」時,這些樣式僅適用於第一個img標籤,該標籤總是存在於其他存在但其他位置,但如果我再次將鼠標懸停在「li」上,則應用這些內嵌樣式在所有img標籤上。爲此我使用這個js給出下面的代碼:在有問題的運行時添加內聯樣式

$(document).ready(function() { 
var mouseover_interval; 
var $image; 

$('li.product-details').mouseenter(function() { 
current_image = -1; 
$image = $(this).find('a.current_product_image img'); 
data_srcs = $image.attr('data-srcs').split(","); 

if(data_srcs.length >1){ 
    for (var i = data_srcs.length - 1; i >= 0; i--) { 
    img = new Image ; 
    img.src = data_srcs[i]; 
    new_img = $('<img>').attr('src', data_srcs[i]).css({display:"none"}).addClass("over"); 
    $(this).find('a.current_product_image').append(new_img); 
    var countImg = $(this).find('a.current_product_image img'); 
    countImg.each(function(){ 
     $(this).css({ 
     position : 'absolute', 
     left : '50%', 
     marginLeft : -$(this).width()/2, 
     top : '50%', 
     marginTop : -$(this).height()/2, 
     }); 
    }); 
    } 
} 
else{ 
    return false; 
} 

$images = $(this).find('a.current_product_image img.over'); 
mouseover_interval = setInterval(function(){ 
{ 
    $image.fadeOut(500); 
    if(current_image == -1){ 
     $($images[$images.length-1]).fadeOut(500); 
    } 
    else{ 
     $($images[current_image]).fadeOut(500); 
    } 

    current_image+=1; 
    $($images[current_image]).fadeIn(500); 

    if(current_image == $images.length-1){ 
     current_image = -1; 
    } 
    } 
}, 1000); 
}).mouseleave(function(){ 
clearInterval(mouseover_interval); 
$image.fadeIn(500); 
$(this).find('a.current_product_image img.over').remove(); 
}); 
}); 

如何在所有附加元素懸停在「li」第一次添加樣式?請讓我知道如果我在那裏使用任何錯誤。

由於提前, Ashwani夏爾馬

回答

1

出現這種情況的原因是 - 最有可能的 - 額外的圖像沒有加載到DOM,但(記住,是需要時間的資產 - 特別是圖像 - 加載當你動態添加它們時)。

要確認這一點,請嘗試記錄countImg var,並查看它是否會報告您期望擁有的圖像數量太少。我懷疑這是你的問題。

您可以嘗試在將元素添加到頁面之前將屬性傳遞到元素中。事情是這樣的:

new_img = $('<img>', { 
    src: data_srcs[i], 
    class: 'over' 
}).hide(); 

這應該創建一個對象,看起來像:

<img src="your/source.jpg" class="over" style="display: none;" /> 

您的問題仍然是,它實際上並不會加載到頁面,直到您關閉display: none,最瀏覽器足夠智能,以便在實際需要時不會拉出圖像(即:不在隱藏時)。

另請注意,您的$image聲明只在函數的開始處設置一次。因此,它將只包含當時在時發現的元素。如果您動態添加其他圖像(即:您的new_img)到父元素,它們將不會自動添加到該$image變量。

+0

right John這是同一個問題,圖片加載到DOM的時間較晚。我只是嘗試記錄countImg,並首次將其懸停在沒有樣式的剛加載的圖像上。那麼,是否有任何預先添加樣式附加項目? –