渐变切换

通过改变透明度的方式切换图片

HTML

<div id="box" class="box">
	<div class="item"></div>
	<div class="item"></div>
	<div class="item"></div>
</div>

CSS

*{
		margin:0;
		padding:0;
	}
	.box{
		margin:50px auto;
		width:200px;
		height:120px;
		position:relative;
		overflow:hidden;
	}
	.item{
		background-color:#000;
		width:200px;
		height:100%;
		position:absolute;
		left:0;
		top:0;
		z-index:0;
		opacity:0;
		filter:alpha(opacity=0);
	}
	.item:nth-child(1){
		z-index:1;
		opacity:1;
		filter:alpha(opacity=100);
	}
	.item:nth-child(2){
		background-color:#f00;
	}
	.item:nth-child(3){
		background-color:#00f;
	}

JavaScript

window.onload = function(){

		var box = document.getElementById("box");
		var items = box.children;
		var now = 0;

		setInterval(function(){
			changeOpacity(items[now], 0);
			now++;
			now = now == items.length ? 0 : now;
			changeOpacity(items[now], 1);
		}, 3000);
	};

	// 改变透明度
	function changeOpacity(obj, target){

		clearInterval(obj.timer);
		var opacity = getStyle(obj, "opacity") * 100;
		var speed = target ? 10 : -10;  // target 为1时,透明度从0到1,所以为正;这种效果没必要弄太细腻,间隔是10就可以

		obj.timer = setInterval(function(){
			
			opacity += speed;
			setOpacity(obj, opacity);

			if(opacity <= 0 || opacity >= 100){

				clearInterval(obj.timer);
				obj.style.zIndex = target;
				setOpacity(obj, target * 100);
			}
		},30)
	}

	function setOpacity(obj, num){
		obj.style.opacity = num / 100;
		obj.style.filter = "alpha(opacity:"+ num +")";
	}

	// 取样式
	function getStyle(obj, attr){
		return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
	}