我是 JS 的新手,我正在尝试使用简单的 JS 脚本转换 body{background:;}
图像。我不想将 div 堆叠在一起然后更改它们的 z-index
,而是想出一个更简单的解决方案,利用 CSS background-size:cover
属性.使用 CSS 属性似乎比使用时更好地缩放背景图像(我是新手,我可能是错误和天真的):
$(window).resize(function() {};
我的问题是,如何使用下面的代码更好地在图像之间进行转换?我想为过渡设置动画,但由于我没有使用堆叠的 div,所以我根本不知道该怎么做。当前图片转换之间存在空白。我尝试预加载图像,但这也没有解决问题。
JavaScript:
function slideShow() {
var images = ['http://www.hdwallpapers.in/walls/fantasy_space-wide.jpg', 'http://phandroid.s3.amazonaws.com/wp-content/uploads/2014/05/rainbow-nebula.jpg']
setInterval(function(){
document.body.style.backgroundImage="url('"+images[0]+"')";
var firstValue = images.shift();
images.push(firstValue);
}, 5000);
}
slideShow();
CSS:
body {
background:#000 no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
如有任何帮助,我们将不胜感激。
最佳答案
我知道您在这里提到了 javascript,但您是否考虑过 CSS3 解决方案? Transitions 提供了一种简单的方法来做到这一点。
这里有一个例子:http://jsfiddle.net/7eqsy2ug/可能是您正在寻找的......如果您想要更平滑的过渡,您也可以尝试淡化不透明度。
JavaScript 的替代方案是:http://rewish.github.io/jquery-bgswitcher/
使用您的 JS 来自 JS Fiddle 的代码:
body {
background:#000 no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
-webkit-transition: background 1s ease-in-out;
-moz-transition: background 1s ease-in-out;
-o-transition: background 1s ease-in-out;
-ms-transition: background 1s ease-in-out;
transition: background 1s ease-in-out;
关于javascript - 使用 JavaScript 平滑地更改 'body' 元素的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25702127/