1 回答

TA贡献1779条经验 获得超6个赞
利用闭包实现就可以了..
//settimeout
<script>
window.onload=function(){
document.getElementById('test').onmouseover=show;
document.getElementById('test').onmouseout=hide;
}
function
setOpacity(elem,num){
if(elem.filters){
return
elem.style.filter='alpha(opacity='+num+')';
}else{
return
elem.style.opacity=parseFloat(num/100);
}
}
function
show(){
var
$this=this;
for(
var
i=0;i<=100;i++){
(function(){
//catch
i;
var
p=i;
setTimeout(function(){
setOpacity($this,p);
},p*2);
})();
}
}
function
hide(){
var
$this=this;
for(var
i=100;i>=0;i--){
(function(){
//catch
i;
var
p=i;
setTimeout(function(){
setOpacity($this,100-p);
},p/2);
})();
}
}
</script>
<style>
#test{
width:200px;
height:200px;
background:#ff0099;
*filter:alpha(opacity=0);
opacity:0;
}
</style>
<body>
<div
id='test'></div>
</body>
//其实这个问题我很久之前有做过...实现淡入的方法很简单...但是淡出..不知道为什么..用同样的方法总是不行...
其实一楼说的jquery很容易实现..我早上也查了一下jquery
原码..当时是查的hide和show..不过它是通过其他的函数来实现的.fade倒是没有找到....今天看到你的问题我重新做了一次...还是那个问题...后来用变量跟踪发现...hide函数i被捕获后..p确实=i.但是进入setTimeout函数后.它就会变成100-P....所以hide函数我给他改成了100-p....但是具体的原因我也很郁闷...
后来用interval的方法来实现....就不存在这个问题了...
//setinterval
var
i=0;
var
showID;
var
hideID;
window.onload=function(){
document.getElementById('test').onmouseover=show;
document.getElementById('test').onmouseout=hide;
}
function
setOpacity(elem,num){
if(elem.filters){
return
elem.style.filter='alpha(opacity='+num+')';
}else{
return
elem.style.opacity=parseFloat(num/100);
}
}
function
show(){
var
$this=this;
showID=setInterval(function(){
if(i<100){
setOpacity($this,i);
i+=5;
}else{
clearInterval(showID);
}
},10);
}
function
hide(){
var
$this=this;
hideID=setInterval(function(){
if(i>=0){
setOpacity($this,i);
i-=5;
}else{
clearInterval(hideID);
}
},10);
}
希望能帮到你
添加回答
举报