在运行时有问题的附加项上添加内联样式
adding inline styling on appended items on run time having issues
我在"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
变量中。
相关文章:
- 如果window.location.href.indexOf('player=1')添加样式
- 如果选中复选框,则添加样式
- 尝试在随机文本和图像脚本中添加样式/更改字体
- 使用javascript为单词添加样式
- IMG悬停添加样式
- 如何在jquery locationpicker插件中为地图添加样式
- Jquery 在 ASP 文本框上添加样式不起作用
- 如何使用JavaScript/jQuery有条件地添加样式表
- 希望在提醒框中添加样式
- struts2 文本区域 仅为一个单词添加样式
- 使用Javascript为样式切换器添加样式表的最佳方法
- 从用户输入向元素添加样式
- Stylus:为在 JavaScript 中生成的 ID 添加样式
- 在 ajax 函数中向 DIV 添加样式更改
- 在更改时使用javascript函数时向html.dropdownlist添加样式
- .html() 在查询中使用 html() 添加样式
- 动态地向 HTML 表添加样式 - 使用 DOM、JS
- 我可以在 innerHTML 中添加样式标签吗?
- angular ng在条件下重复添加样式
- 制作一个Firefox插件来注入一些DIV并添加样式.那'是的