我有一个动画,其中三个图像上下旋转。 JSfiddle:http://jsfiddle.net/rLgkyzgc/1/
$(window).load(function() {
// Load images in BG that have been hidden by CSS
$('.banners').show();
// Create an empty array
var banners = [];
// Fill array with banner ids
$('.banners').each(function () {
var banner = $(this).attr('id');
banners.push(banner);
});
function switchBanners(){
var $firstBanner = $('#' + banners[0]);
var $secondBanner = $('#' + banners[1]);
var firstBannerHeight = $firstBanner.height();
var secondBannerHeight = $secondBanner.height();
$firstBanner.animate({ bottom: -firstBannerHeight }, 1200);
$secondBanner.animate({ bottom: 0 }, 1200, function(){
b = banners.shift(); banners.push(b);
setTimeout(function(){
switchBanners();
}, 4000);
});
};
// Delay initial banner switch
setTimeout(function(){
switchBanners();
}, 4000);
});
这对于桌面 View 非常有用,但在移动设备上,我想停止动画并只显示一张静态图像。
所以我的问题。我怎样才能:
- 仅当窗口宽度 > 940px 时才在页面加载时启动动画
- 如果页面大小调整为 < 940 像素宽,则停止(重置)动画
- 然后,如果页面大小调整为 > 940 像素宽,则重新启动动画
最佳答案
您应该使用 window.matchMedia
(请参阅 documentation )来检测 document.ready
上的视口(viewport)大小以及调整窗口大小时,像这样:
function resetAnimation() {
$firstBanner.stop(true, true);
$secondBanner.stop(true, true);
if(window.matchMedia("(min-width: 940px)").matches) {
//Start the animations here
}
}
$(document).ready(function() {
resetAnimation();
}
$(window).resize(function() {
resetAnimation();
}
请注意,您实际上并不需要在 document.ready 上停止
动画,但这样您就有一个函数来重置动画,然后仅在必要时重新启动它们,这是无论视口(viewport)大小如何,您通常都希望每次调整浏览器窗口大小时都这样做。
关于javascript - 在窗口调整大小时停止/重新启动动画循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181500/