我如何让背景图片淡入?

时间:2013-11-17 03:17:15

标签: javascript random background fadein fadeout

<html>
<head>
<script type="text/javascript" >
function changeImg(imgNumber) {
var myImages = ["1.jpg", "2.jpg", "3.jpg"];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);

document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
document.body.style.backgroundSize = '100% 100%'; 
document.body.style.backgroundRepeat = 'no-repeat';
document.body.style.backgroundAttachment= 'fixed';

}
setInterval(changeImg,5000)
window.onload = changeImg;
</script>
</head>
<body>
</body>

我希望旧图片淡出,新图片会淡入。出于某种原因,我无法弄明白。感谢。

2 个答案:

答案 0 :(得分:2)

使用jquery和css,你可以改变背景。

jQuery :(在图片加载函数中)

$('body').css('background-image', "url('" + $images[0].src + "')");
$('#wrapper').removeClass("bgFade", 700);

CSS:

.bgFade{
    background-color:#FFF;

}

答案 1 :(得分:0)

Here's an easy solution with JQuery (If you're not opposed to it.)

JQuery的

jQuery(document).ready(function(){ 
    $(function(){
        $('.fadein a:gt(0)').hide();
        setInterval(function(){
          $('.fadein :first-child').fadeOut(1000)
             .next('a').fadeIn(1000)
             .end().appendTo('.fadein');}, 
          2000);
    });
});

HTML

<div class="fadein">
    <a href="" id="rotatingImage1"></a>
    <a href="" id="rotatingImage2"></a>
    <a href="" id="rotatingImage3"></a>
</div>

CSS

#rotatingImage1{background:url('http://lorempixel.com/500/501/') no-repeat;position:absolute;width:500px;height:500px;}
#rotatingImage2{background:url('http://lorempixel.com/500/502/') no-repeat;position:absolute;width:500px;height:500px;}
#rotatingImage3{background:url('http://lorempixel.com/500/503/') no-repeat;position:absolute;width:500px;height:500px;}