[英]Fading Background Images
我使用一个简单的脚本每隔X秒更改一次我的网站的背景图片。 我想做的是合并某种淡入淡出动画或从一个图像过渡到下一个图像。 实现此目标的最佳方法是什么?
我对Javascript不太满意,所以请多多包涵。 :)
<script type="text/javascript">
var images = ['bg1.png', 'bg2.png', 'bg3.png'];
var curImage = 0;
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(images/' + images[curImage] + ')'
}
window.setInterval(switchImage, 5000);
</script>
我一遍又一遍地读着,听不懂,所以请有人给我一个工作代码,这样我就可以复制粘贴,摆脱这个烦人的工作。 此处的示例http://preferredmerchantservices.net/
似乎没有人使用老式的js脚本来实现这种动画。 我建议您使用jQuery或其他javascript库,它们基本上是浏览器javascript功能的抽象层。
另外,您还可以找到许多示例,例如插件,过渡效果等插件。
希望能帮助到你。
万一您需要为jQuery重写的代码。 开始:
<script type="text/javascript">
var images = ['bg1.png', 'bg2.png', 'bg3.png'];
var curImage = 0;
var timer;
function switchImage() {
$('body').css({'backgroundImage':'url(images/' + images[curImage] + ')'};
curImage == images.length? curImage = 0; curImage++;
clearInterval(timer);
timer = setInterval(switchImage, 5000);
}
timer = setInterval(switchImage, 5000);
</script>
我想指出的是,这不会淡入/淡出背景图像。 为此,您可以使用一个容器作为背景图像。 可能会调整大小。
// Resize Handler
$(window).resize(function () {
resizePages();
});
function resizePages() {
var width = $(window).width();
var height = $(window).height();
$('.backgroundContainer').css({'width': width});
/*
.contentWrapper would be where all your page's content is placed
.backgroundContainer is a class for a div placed out side teh contentWrapper
It would have a lower z-index than .contentWrapper but higher than body.
*/
/*
This makes sure that the background image is the same height as
either the windows of the .contentWrapper (whichever is larger)
*/
if (height > $('.contentWrapper').height()){
$('.backgroundContainer').css({'height': height});
} else {
$('.backgroundContainer').css({'height': $('.contentWrapper').height()});
}
}
然后,您可以调整开关代码以淡入过渡之间的背景。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.