css代码:
#bg{ margin-left: 29%; position: relative; } #bg img{ width: 800px; height: 500px; position: absolute; transition: all 1s; } #bg img:nth-child(1){ z-index: 4; } #bg img:nth-child(2){ z-index: 3; } #bg img:nth-child(3){ z-index: 2; } #bg img:nth-child(4){ z-index: 1; } .fadeOut{ opacity: 0; }
html代码:
<div id="bg"> <img src="手风琴/spring.jpg"/> <img src="手风琴/summer.jpg"/> <img src="手风琴/autumn.jpg"/> <img src="手风琴/winter.jpg"/> </div>
javascript代码:
function animation(){ var bg = document.getElementById("bg"); var aImg = bg.getElementsByTagName("img"); var number = 0; function fadeOut(){ aImg[number].className = "fadeOut"; }; function fadeIn(){ aImg[number].className = ""; } function pictureSwitching(){ fadeOut(); number++; if(number == 4){ number = 0; for(var i = 0;i < 4;i++){ number= i; fadeIn(); } number = 0; } }
setInterval(function(){ pictureSwitching(); },2000) } animation();
让第一张图片淡出,1s后让下一张(aImg[number])淡出,全部淡出后,让他们全部淡入。