我是一个 JS 新手,所以在这里对我放轻松。但是我写了一个简单的幻灯片,它似乎运行得很慢。下面的代码在我自己的机器上本地加载大约需要 2-4 秒。想知道是什么导致延迟。告诉我,谢谢!
function slideshow(){
$("#1").animate({top: "50px",}, 500).delay(2000);
$("#1").animate({top: "400px",}, 500);
$("#2").animate({top: "50px",}, 500).delay(2000);
$("#2").animate({top: "400px",}, 500);
$("#3").animate({top: "50px",}, 500).delay(2000);
$("#3").animate({top: "400px",}, 500);
$("#4").animate({top: "50px",}, 500).delay(2000);
$("#4").animate({top: "400px",}, 500);
$("#5").animate({top: "50px",}, 500).delay(2000);
$("#5").animate({top: "400px",}, 500);
slideshow();
}
每个 ID 代表不同的图像。
最佳答案
你的代码的大问题是 slideshow()
的最后一行递归调用自身,因为其他答案似乎都没有谈到它,这将导致堆栈溢出。不要这样做:
function slideshow() {
// animate code
slideshow();
}
相反,如果您希望它重复运行,请使用 setTimeout()
将函数的另一次执行排队 x 毫秒后:
function slideshow() {
// animate code
setTimeout(slideshow, 3500);
}
按照您的方式,没有任何功能真正完成。使用 setTimeout()
,每次调用 slideshow()
都会完成,然后在指定的延迟后运行一个单独的调用。我会将延迟设置得足够大,以便在当前动画完成后进行下一次调用,否则您将排队等待越来越多的动画,而不是它们运行的速度。
更新:jQuery 为每个元素维护单独的动画队列,这意味着您的五个元素上的动画将同时运行。其他一些答案已经提供了一次按顺序运行动画的方法,但我会这样做:
$(window).on("load",function() {
// cache a jQuery object containing the elements to animate
// (note you don't need their ids if you use their class)
var $imgs = $('img.slideshow-image'),
i = 0;
function slideShow() {
// start animation for "current" img
$imgs.eq(i).show(1)
.animate({top: "50px",}, 500)
.delay(2000)
.animate({top: "400px",}, 500)
.hide(1, function() {
i = (i+1) % $imgs.length;
setTimeout(slideShow, 500);
});
}
slideShow();
});
工作演示:http://jsfiddle.net/bARwb/
- 我将代码包装在一个加载处理程序中,既消除了对内联
onload=
属性的需要,又作为一种将代码保持在全局范围之外的便捷方式(如果您这样做的话)这样不要忘记从你的 body 标签中删除onload="slideShow()"
。 - 我添加了
.show()
和.hide()
调用(有一个持续时间,以便它们加入动画队列)这样 img 元素将在动画之间有display:none
因为否则你的position:relative
风格除了第一个你什么都看不到(但改变为position:absolute
会阻止他们被 parent 的overflow:hidden
裁剪)。 - 当一个元素的动画完成时,
.hide()
的回调会递增i
以引用下一个元素的索引(但会检查它何时超过最后一个元素),然后使用setTimeout()
为下一个元素排队动画。
关于javascript - JS代码运行很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111255/