我有以下代码片段无休止地循环遍历jQuery animate函数。它在Chrome上工作正常,但在IE上第一次动画调用后失败。我的问题是:
如何在第一次循环后添加延迟?我希望连续脉冲之间有延迟。
#container {
position : relative;
width : 500px;
height : 200px;
overflow : hidden;
opacity: 1;
}
#container > img {
position : absolute;
top : 0;
left : 0;
}
$(window).load(function(){
$(function () {
var $image = $('#container').children('img');
function animate_img() {
if ($image.css('opacity') == '1') {
$image.animate({opacity: '0.4'}, 2000, function () {
animate_img();
});
} else {console.log('2');
$image.animate({opacity: '1'}, 2000, function () {
animate_img();
});
}
}
animate_img();
});
});
<div id="container">
<img src="blah.jpg" width="500" height="375" />
</div>
答案 0 :(得分:1)
从console.log()
分支中删除else
语句,它应该在IE中运行 - IE不像console.log()
,除非控制台实际上是打开的,而(大多数)其他浏览器要么忽略它,要么以稍后打开控制台时可以看到的方式登录。 (我没有IE9,但是当我在IE8中测试它时,只需要修复它。)
在$(window).load()
处理程序中放置一个文档就绪处理程序也没有意义,所以你应该删除其中一个。
至于在连续脉冲之间添加延迟,只需在调用else分支中的.animate()
之前使用jQuery&#39; .delay()
function,如下所示:
$(function () {
var $image = $('#container').children('img');
function animate_img() {
if ($image.css('opacity') == '1') {
$image.animate({opacity: '0.4'}, 2000, function () {
animate_img();
});
} else { // console.log removed from this spot
$image.delay(500).animate({opacity: '1'}, 2000, function () {
animate_img();
});
}
}
animate_img();
});
P.S。鉴于您.animate()
完整回调所获得的匿名函数除了调用animate_img()
之外什么也不做,您可以删除匿名函数并直接传递animate_img
。因此,如果您愿意,可以将功能缩短:
$(function () {
var $image = $('#container').children('img');
function animate_img() {
var fade = $image.css('opacity') == '1';
$image.delay(fade?1:500).animate({opacity:fade?'0.4':'1'},2000,animate_img);
}
animate_img();
});
答案 1 :(得分:0)
关于是否应使用setTimeout()
或setInterval()
的已删除讨论后,使用setInterval()
$(function () {
var $image = $('#container').children('img');
function animate_img() {
if ($image.css('opacity') == 1) {
$image.animate({opacity: 0.4},{ queue:false, duration:2000});
} else {
$image.animate({opacity: 1},{ queue:false, duration:2000});
}
}
setInterval(animate_img, 4000);
});
请注意,间隔时间应至少为4000毫秒,这是动画时间(每个2000毫秒)来回的总和。如果间隔小于该间隔,动画将无法完成。
我在之前(已删除)的讨论中坚持认为setInterval
的正确语法应该是setInterval("animate_img()", 4000)
...我的不好,因为我错过了setInterval
在函数中...因此,函数animate_img
应该被称为指针而不是字符串。
这个解决方案的优点(我认为)是更少的代码行,但我们也不需要在循环中从内部调用函数animate_img()
3次。
这应该可以在Chrome和IE中正常使用。