通过代码实行多张图片淡入淡出切换,ie兼容(亲测ie6以上有效,包括ie6)
两张图片切换,其实最好的方法是flash插件,做个flash,代码少,效果好,兼容也还可以(我亲测ie6以上是可以的,哈哈~),但甲方大大嫌安装太烦,且怕大多数用户不会安装,无奈,只能薅头发用代码写了,上网查了好多资料,终于完成了
话不多说,上代码
css部分
<style>
/*.td-class{*/
/* width:20px;*/
/* height: 20px;*/
/*}*/
/*td.active {*/
/* background: orange;*/
/*}*/
.showImg{
position: absolute;
opacity: 0;
}
</style>
html部分
<!--<table id="tab" border="1">
<tr>
<td index=0 class="td-class"></td>
<td index=1 class="td-class"></td>
<td index=2 class="td-class"></td>
<td index=3 class="td-class"></td>
</tr>
</table>-->
<div style="position: relative;">
<img class="showImg first" src="./img/1.jpg" style="width:300px"/>
<img class="showImg" src="./img/2.jpg" style="width:300px"/>
<!-- <img class="showImg" src="./img/3.jpg" style="width:300px"/>
<img class="showImg" src="./img/4.jpg" style="width:300px"/>-->
</div>
css和html部分就不多说了,其中注释的部分是添加了点击切换的效果,因为我没用到,所以注释了
下面最重要的是js部分了,不懂得看注释
<script type="text/javascript">
window.onload = function(){
// var tab=document.getElementById("tab");
var num=0;
// tab.children[0].children[0].children[0].className="td-class active";
var showImgs=document.getElementsByTagName("img");//获取img元素,😂注意不能用document.getElementsByClassName(),ie7不兼容,好坑,这个地方卡了我好久,才发现这个错误,当然你有jq就没有这个报错了
// tab.addEventListener("click",function(e){
// var e=e||event;
// if(e.target.nodeName=="TD"){
// for(var i=0;i<4;i++){
// e.target.parentNode.children[i].className="td-class";
// }
// e.target.className="td-class active";
// var index=e.target.getAttribute("index");
// num=index;
// fadeIn(showImgs[index]);
// for(var i=0;i<4;i++){
// if(i!=index){
// fadeOut(showImgs[i]);
// }
// }
// }
// })
//没有操作时,图片的自我变换
setInterval(function(){
// for(var i=0;i<4;i++){
// tab.children[0].children[0].children[i].className="td-class";
// }
// tab.children[0].children[0].children[num].className="td-class active";
fadeIn(showImgs[num]);
for(var i=0;i<2;i++){
if(i!=num){
fadeOut(showImgs[i]);
}
}
num++;
if(num>=2){num=0;}
},2000)
//获取非行内样式,获取img opacity值,这边我认为是整个代码的重中之重,判断ie 谷歌浏览器
function getStyle(ele){
if(ele.currentStyle){
return ele.currentStyle;//ie兼容,谷歌不兼容
}else return getComputedStyle(ele);//谷歌兼容,ie不兼容
}
//淡出效果
function fadeOut(ele,callback){ //采用回调函数
var val=Number(getStyle(ele).opacity);
var val1=val*100
clearInterval(ele.timer);
ele.timer=setInterval(function(){
val-=0.04;
val1=val*100
ele.style.opacity=val;
ele.style.filter = "alpha(opacity="+ val1 +")"
if(val<=0){
clearInterval(ele.timer);
callback?callback():"";
}
},30)
}
//淡入效果
function fadeIn(ele,callback){
var val=Number(getStyle(ele).opacity);
var val1=val*100
ele.timer=setInterval(function(){
val+=0.04;
val1=val*100
ele.style.opacity=val;
ele.style.filter = "alpha(opacity="+ val1 +")"
if(val>=1){
clearInterval(ele.timer);
callback?callback():"";
}
},30)
}
}
</script>