原生js实现图片切换效果:淡入浅出效果。


将以下代码保护为html文件后,可直接看到效果。

代码:


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>www.jshaman.com</title>
<style>
body,ul,ol{margin:0;padding:0;}
li{ list-style:none;}
img{ border:none; vertical-align:top; }
#box{width:470px;height:150px; position:relative; margin:30px auto; overflow:hidden;}
ul{ width:470px; position:absolute;left:0; top:0; z-index:1;}
ul li{width:470px; display:none; position:absolute; top:0; left:0; filter:alpha(opacity=0); opacity:0;}
ol{z-index:2; width:120px; position:absolute;right:10px; bottom:10px;}
ol li{ width:20px;height:20px; float:left;margin:0 2px; display:inline; background:#fff; color:#f60; line-height:20px; text-align:center;}
ol .active{ background:#f60; color:#fff;}
</style>
<script>
function startMove(obj,json,endFn){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var bBtn = true;
for(var attr in json){

var iCur = 0;

if(attr == 'opacity'){
if(Math.round(parseFloat(getStyle(obj,attr))*100)==0){
iCur = Math.round(parseFloat(getStyle(obj,attr))*100);

}
else{
iCur = Math.round(parseFloat(getStyle(obj,attr))*100) || 100;
}
}
else{
iCur = parseInt(getStyle(obj,attr)) || 0;
}

var iSpeed = (json[attr] - iCur)/8;
iSpeed = iSpeed >0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if(iCur!=json[attr]){
bBtn = false;
}

if(attr == 'opacity'){
obj.style.filter = 'alpha(opacity=' +(iCur + iSpeed)+ ')';
obj.style.opacity = (iCur + iSpeed)/100;
}
else{
obj.style[attr] = iCur + iSpeed + 'px';
}
}

if(bBtn){
clearInterval(obj.timer);

if(endFn){
endFn.call(obj);
}
}
},30);
}


function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj,false)[attr];
}
}
</script>
<script>
window.onload = function(){
var oUl = document.getElementsByTagName('ul')[0];
var aLiUl = oUl.getElementsByTagName('li');

var oOl = document.getElementsByTagName('ol')[0];
var aLiOl = oOl.getElementsByTagName('li');

for(var i=0;i<aLiOl.length;i++){
aLiOl[i].index = i;
aLiOl[i].onmouseover = function(){
for(var i=0;i<aLiOl.length;i++){
aLiOl[i].className = '';

startMove( aLiUl[i],{opacity:0},function(){
this.style.display = 'none';

} );

}
this.className = 'active';
aLiUl[this.index].style.display = 'block';
startMove(aLiUl[this.index],{opacity:100});
};
}

};
</script>
</head>
<body>
<div id="box">
<ul>
<li style="display:block; filter:alpha(opacity=100); opacity:1;"><img src="http://fairysoftware.com/fairysoftware_2016/img/hackgame_banner.jpg" alt=""/></li>
<li><img src="http://www.fairysoftware.com/images/banners/banner_yxdj.jpg" alt=""/></li>
<li><img src="http://www.fairysoftware.com/images/banners/banner_sgmj.jpg" alt=""/></li>
</ul>
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
</body>
</html>