我有一个脚本,可以创建带有一些背景图像的 div,然后移动它们,它在所有其他浏览器上运行良好,但 chrome 太慢了。我检查了我的代码,发现当我删除以下代码时,它在 chrome 上也能很好地工作。
//imageCount = count of image placed for animation, this loop gets source of
//each image, create divs, then makes each image to background of a div
for(imageNum=0;imageNum<imageCount;imageNum++)
{
var imageSrc= $("#image img:eq("+imageNum+")").attr("src");
//save image sources for later use
images.push(imageSrc);
//creating divs
$("#main_cont").append("<div name=img"+imageNum+" class=img_cont></div>");
//here is my problem
//when i delete .css part works great
$("#main_cont .img_cont:eq("+imageNum+")").width(tWidth).height(tHeight).css({
backgroundImage: "url("+imageSrc+")",
backgroundRepeat: "no-repeat",
backgroundSize: tWidth +"px "+ tHeight +"px "
});
//this part is not about my question, each div's position for animation
var offset = $("#main_cont .img_cont:eq("+imageNum+")").offset();
yPos.push(offset.top);
xPos.push(offset.left);
}
我在 jsfiddle 上的代码的一个简单版本:http://jsfiddle.net/uUj4h/2/ (可能需要一分钟加载大图像的原因)
如果我找不到解决方案,我会在 div 中使用图像而不是背景,但为了我的动画,但我需要 div。
最佳答案
你尝试过显而易见的事情吗:
$("#main_cont .img_cont:eq("+imageNum+")").css({
width: tWidth,
height: tHeight,
background: "url("+imageSrc+") no-repeat top left"
});
只需在您的 css 中设置背景大小即可。
fiddle :http://jsfiddle.net/adeneo/6TeBk/2/
或者您可以尝试将它作为 img 标签附加到元素的开头:
var imageSrc = new Image();
imageSrc.src = $("#image img:eq("+imageNum+")").attr("src");
imageSrc.width = tWidth;
imageSrc.height = tHeight;
$("#main_cont .img_cont:eq("+imageNum+")").css({ width: tWidth, height: tHeight}).append(imageSrc);
关于chrome 上的 Jquery .css 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8449822/