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

标签 javascript jquery css

我在“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”上的所有附加元素上添加样式?如果我在那里使用有任何错误,请告诉我。

提前致谢, 阿什瓦尼夏尔马

最佳答案

发生这种情况的原因很可能是附加图像尚未加载到 DOM 中(请记住,动态添加 Assets (尤其是图像)需要时间来加载它们)。

要确认这一点,请尝试记录 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 变量中。

关于javascript - 在运行时有问题的附加项上添加内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912403/

相关文章:

javascript - Node.js中如何实现两个数组之间的增删改查?

javascript - 获取与当前日期 ACF 相比最接近的日期

jquery - HTML 5 Canvas 和 QR 码

javascript - 字符串格式自定义方法扩展

css - 是否可以将图像置于 overflow hidden 的包装内?

javascript - SendBird 以文件为封面创建 GroupChannel

jquery - 允许 CORS REST 请求到 express/node.js 应用程序

css - 样式输入文本 CSS

php - 回显 '<pre>' 以保留中断与中断字冲突

javascript - 什么 javascript 将模拟从 google maps api 3 places autocomplete 下拉列表中进行选择?