当页面第一次加载时,图像会出现累积添加.Jquery不会动态计算宽度,而是正常显示第二次加载或页面刷新后。可能是什么原因?
使用Javascript:
$(function(){
var imageWidth, totalWidth, sliderContent, $slider;
$slider = $("#slider");
sliderContent = $slider.html();
$slider.html("<div id=\"slideWrapper\">" + sliderContent + "</div>");
imageWidth = $slider.find("img").width();
totalWidth = $slider.find("img").size() * imageWidth;
$("#slider").css("width", imageWidth);
$("#slideWrapper").css("width", totalWidth);
$(".next-arr").click(function () {
if (parseInt($("#slideWrapper").css("margin-left")) < 0 && !$("#slideWrapper").is(":animated")) {
$("#slideWrapper").stop(true, true).animate({ marginLeft: "+=" + imageWidth + "px" }, 1600);
}
});
$(".prev-arr").click(function () {
if ((parseInt($("#slideWrapper").css("margin-left")) * -1) < (totalWidth - imageWidth) && !$("#slideWrapper").is(":animated")) {
$("#slideWrapper").stop(true, true).animate({ marginLeft: "-=" + imageWidth + "px" }, 1600);
}
});
});
HTML:
<div id="slider">
<a href="#" title="img">
<img src="img.jpg" alt="img" /></a>
<a href="#" title="img">
<img src="img.jpg" alt="img" /></a>
<a href="#" title="img">
<img src="img.jpg" alt="img" /></a>
<a href="#" title="img">
<img src="img.jpg" alt="img" /></a>
</div>
的CSS:
#slider {
overflow: hidden;
}
#slider a, #slider img {
float: left;
overflow: auto;
position: relative;
}
#slideWrapper {
overflow: hidden;
}
#slideWrapper img {
float: left;
}
答案 0 :(得分:1)
您可以使用$(window).load
的其他方式,可能是您的功能在加载图像之前执行,因此第二次图像从缓存中出现,因此它们不会花费时间在第一次加载图像上没有出现在缓存中。 / p>
$(window).load(function(){
var imageWidth, totalWidth, sliderContent, $slider;
$slider = $("#slider");
sliderContent = $slider.html();
$slider.html("<div id=\"slideWrapper\">" + sliderContent + "</div>");
imageWidth = $slider.find("img").width();
totalWidth = $slider.find("img").size() * imageWidth;
$("#slider").css("width", imageWidth);
$("#slideWrapper").css("width", totalWidth);
// other code .....
});
希望这是有道理的