2013-06-04 34 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,并首次将其悬停在没有样式的刚加载的图像上。那么,是否有任何预先添加样式附加项目? –