在运行时有问题的附加项上添加内联样式

adding inline styling on appended items on run time having issues

本文关键字:添加 样式 运行时 有问题      更新时间:2023-09-26

我在"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 Sharma

发生这种情况的原因很可能是其他图像尚未加载到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变量中。