How to loop iframes using jquery?
I have two iframes. When the page loads, iframe1 gets loaded after 8 seconds, and I need to show iframe2 replacing iframe1 on an indefinite loop.
I tried the following code and set the timeout as 8 seconds and 10 seconds, but iframe1 changes within 2 seconds.
function preview() {
$('#iframe1').hide();
$('#iframe2').show();
setTimeout(function() {
$('#iframe2').hide();
$('#iframe1').show();
}, 8000);
};
setInterval(preview, 10000)
The above doesn't load smoothly either. How can I show/hide them seamlessly?
You can perform this action using recursion function and pass the arguments
$('#iframe2').hide();
animateInfinite('#iframe', 1)
function animateInfinite(str, last) {
$(str + last).show();
setTimeout(function () {
$(str + last).hide();
animateInfinite('#iframe', ((last == 1) ? 2 : 1));
}, 8000)
}
Or use setinterval
var iframe = $('[id^=iframe]').hide();
iframe.eq(0).show();
setInterval(function () {
iframe.toggle();
}, 1000);
DEMO
你可以切换;
function preview() {
$('#iframe1').toggle(500);
$('#iframe2').toggle(500);
};
setInterval(preview, 10000)
@Anil Kumar's answer is good but not quite there yet, toggle()
animates the change, if you do it at the same time like that without waiting for one to be done to toggle the other you'll have 2 iframes sitting there.
In addition to @Anil All I want to add is the following modification:
function preview(duration, hide) {
var hide = hide || 1;
var show = hide === 1 ? 2 : 1;
$('#iframe'+hide).toggle(500, function() {
$('#iframe'+show).toggle(500);
setTimeout(function() {
preview(duration, show);
}, duration);
});
}
This is untested but what it should do anyways is apply the toggle for you, switching ID's of the elements every call which first animates the visible element and then animates the invisible element afterwards.
This makes sure the elements don't collide or break the flow of elements. Furthermore I added an argument of duration
to your function - this way you can call the function like this:
preview(10000)
if #iframe2
is visible first you use that ID number to make it animate first, it defaults to one as visible in the function.
preview(10000, 2)
This also keeps recreating the jQuery objects all the time which mobile phones don't really like (it can slow em down quite bad) so try to cache those in variables outside of the function and pass them in perhaps, using another trick that switches elements.
链接地址: http://www.djcxy.com/p/26846.html上一篇: 提取R函数的代码用于控制宽度的针织物
下一篇: 如何循环使用jQuery的iframe?