问题:即为淡入淡出的效果实现
解决方案:用定时器
<!DOCTYPE html>
<html>
<head>
<title>淡入淡出</title>
<style>
#yellowdiv,#reddiv{
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="yellowdiv"></div>
<div id="reddiv"></div>
<script type="text/javascript">
var fadingObject = {
yellowColor:function(val){
var r = "ff";
var g = "ff";
var b = val.toString(16);
var newval = "#"+r+g+b;
return newval;
},
fade:function(id,start,finish){
console.log(this);
this.count = this.start=start;
this.finish = finish;
this.id = id;
this.countDown = function(){
this.count +=30;
if(this.count >=this.finish){
document.getElementById(this.id).style.background="transparent";
this.countDown = null;
return;
}
document.getElementById(this.id).style.backgroundColor = this.yellowColor(this.count);
setTimeout(this.countDown.bind(this), 100);
}
}
};
window.onload = function(){
fadingObject.fade("yellowdiv",0,300);
fadingObject.countDown();
}
</script>
</body>
</html>
注意bind的用法,保证this的正确性,相当于把fadingObject的实例传给了countDown()方法
如果不用bind上面的代码可以改写为
<!DOCTYPE html>
<html>
<head>
<title>淡入淡出</title>
<style>
#yellowdiv,#reddiv{
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="yellowdiv"></div>
<div id="reddiv"></div>
<script type="text/javascript">
var fadingObject = {
yellowColor:function(val){
var r = "ff";
var g = "ff";
var b = val.toString(16);
var newval = "#"+r+g+b;
return newval;
},
fade:function(id,start,finish){
console.log(this);
this.count = this.start=start;
this.finish = finish;
this.id = id;
this.count = this.start = start;
this.finish = finish;
this.id = id;
this.countDown = function(i){
var that = this;
setTimeout(function(i){
that.count +=30;
console.log(this.count);
console.log(that.count);
if(that.count>=that.finish){
document.getElementById(that.id).style.background = "transparent";
//that.count = 0;
that.countDown = null;
return;
}
console.log(that.id);
document.getElementById(that.id).style.backgroundColor = that.yellowColor(that.count);
},i*300);
}
}
};
window.onload = function(){
fadingObject.fade("yellowdiv",0,300);
for(var i =0;i<10;i++){
fadingObject.countDown(i);
}}
</script>
</body>
</html>