首页 > 代码库 > JavaScript渐变效果的实现

JavaScript渐变效果的实现

鼠标移上去透明度渐渐增加,鼠标移出,透明度渐渐减小。

关键代码:咸宁市中心小学

view source
 
print?
1var speed = 0;
2if(target>obj.alpha){
3    speed = 5;
4}else{
5    speed = -5;
6}

根据目标值和当时值的对比,来决定是正向还是负向速度。

view source
 
print?
01for(i=0; i < runs_li.length; i++){
02    runs_li[i].timer = null;
03    runs_li[i].alpha = 30;
04    runs_li[i].onmouseover = function(){
05        startrun(this,100);
06    }
07    runs_li[i].onmouseout = function(){
08        startrun(this,30);
09    }
10}

给每一个元素加上各自的透明度值,各自的透明度变化分开。

全部代码:

view source
 
print?
01<style>
02#runs{width:300px; margin:10px auto;}
03#runs li{width:80px; height:80px; background:#06c; list-style:none; float:left; margin:10px; display:inline; filter:alpha(opacity=30); opacity:0.3;}
04</style>
05<script>
06window.onload = function(){
07  var runs = document.getElementById("runs");
08  var runs_li = runs.getElementsByTagName("li");
09  var i=0;
10  for(i=0; i<runs_li.length; i++){
11    runs_li[i].timer = null;
12    runs_li[i].alpha = 30;
13    runs_li[i].onmouseover = function(){
14      startrun(this,100);
15    }
16    runs_li[i].onmouseout = function(){
17      startrun(this,30);
18    }
19  }
20}
21 
22function startrun(obj,target){
23  clearInterval(obj.timer);
24  obj.timer = setInterval(function(){
25    var speed = 0;
26    if(target>obj.alpha){
27      speed = 5;
28    }else{
29      speed = -5;
30    }
31   
32    if(obj.alpha == target){
33      clearInterval(obj.timer);
34    }else{
35      obj.alpha = obj.alpha + speed;
36      obj.style.filter = "alpha(opacity="+obj.alpha+")";
37      obj.style.opacity = obj.alpha/100;
38    }
39 
40  },30)
41}
42 
43</script>
44 
45<ul id="runs">
46  <li>简</li>
47  <li>明</li>
48  <li>现</li>
49  <li>代</li>
50  <li>魔</li>
51  <li>法</li>
52</ul>

JavaScript渐变效果的实现