2016-04-30 227 views
0

我想淡出div的背景圖像時,我的圖像出現在該div內的內容也淡化如何停止內容的淡入淡出效果。淡入淡出背景圖像淡入淡出div內容

JS Fiddle

HTML:

<div id="background">adsdsa</div> 

JS:

var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p2.jpg"]; 
var i = 0; 

// Start the slide show 
var interval = self.setInterval(swapBkgnd, 5000) 

function swapBkgnd() { 
    if (i > (bgArr.length - 1)) { 
    i = 0 
    $('#background') 
    .animate({opacity: 0}, 'slow', function() { 
     $(this) 
      .css({'background-image': "url(" + bgArr[i] + ")"}) 
      .animate({opacity: 1}); 
    }); 
    } else { 
    $('#background') 
    .animate({opacity: 0}, 'slow', function() { 
     $(this) 
      .css({'background-image': "url(" + bgArr[i] + ")"}) 
      .animate({opacity: 1}); 
    }); 
    } 
    i++; 
}; 

CSS:

#background { 
    position: absolute; 
    min-height: 100%; 
    width: 100%; 
    height: auto; 
    top: 0; 
    left: 0; 

    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
} 

回答

0

如果你把裏面的div內容是fadding然後喲你無法阻止內容被加入。如果您將內容放在div之外並使用position: absolute;對齊,則可以實現您的願望目標。看看演示 -

var bgArr = ["http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p1.jpg", "http://malsup.github.io/images/p2.jpg"]; 
 
var i = 0; 
 

 
// Start the slide show 
 
var interval = self.setInterval(swapBkgnd, 1000) 
 

 
function swapBkgnd() { 
 
    if (i > (bgArr.length - 1)) { 
 
    i = 0 
 
    $('#background') 
 
     .animate({ 
 
     opacity: 0 
 
     }, 'slow', function() { 
 
     $(this) 
 
      .css({ 
 
      'background-image': "url(" + bgArr[i] + ")" 
 
      }) 
 
      .animate({ 
 
      opacity: 1 
 
      }); 
 
     }); 
 
    } else { 
 
    $('#background') 
 
     .animate({ 
 
     opacity: 0 
 
     }, 'slow', function() { 
 
     $(this) 
 
      .css({ 
 
      'background-image': "url(" + bgArr[i] + ")" 
 
      }) 
 
      .animate({ 
 
      opacity: 1 
 
      }); 
 
     }); 
 
    } 
 
    i++; 
 
};
#background { 
 
    position: absolute; 
 
    min-height: 100%; 
 
    width: 100%; 
 
    height: auto; 
 
    top: 0; 
 
    left: 0; 
 
    -webkit-background-size: cover; 
 
    -moz-background-size: cover; 
 
    -o-background-size: cover; 
 
    background-size: cover; 
 
} 
 
span { 
 
    position: absolute; 
 
    top:0; 
 
    left:0; 
 
    z-index: 2; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="background"></div> 
 
<span>adsdsa</span>