JavaScript淡入淡出效果

快乐打工仔 分类:实例代码

JavaScript淡入淡出效果属于前端实例代码,有关更多实例代码大家可以查看

本章节介绍一下如何使用原生JavaScript实现淡入淡出功能。

代码实例如下:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.pipipi.net/" /> 
<title>js代码控制元素简单的淡入淡出效果</title>
<style type="text/css">
*{
  margin:0;
  padding:0
}
body{
  font:12px Verdana, Arial;
  color:#777;
  background:#222
}
a{
  color:#999;
  text-decoration:none
}
a:hover{color:#bbb}
#wrapper{
  width:500px;
  margin:75px auto
}
#buttons{height:35px}
.button{
  border:1px solid #eee;
  background:#ccc;
  border-radius:3px;
  -moz-border-radius:3px;
  padding:4px 0 5px;
  width:245px;
  text-align:center;
  cursor:pointer;
  float:left;
  color:#555
}
.button:hover{
  border:1px solid #fff;
  background:#d9d9d9;
  color:#333
}
.floatright{float:right}
#fade{
  opacity:0;
  filter:alpha(opacity='0') border-radius:3px;
  -moz-border-radius:3px;
  margin-bottom:10px;
  padding:9px 10px 0;
  height:26px;
  border:1px solid #548954;
  background:#355c33;
  color:#79af72;
  text-shadow:1px 1px #21341d
}
</style>
<script type="text/javascript">
var fadeEffect=function(){
  return{
    init:function(id, flag, target){
      this.elem = document.getElementById(id);
      clearInterval(this.elem.si);
      this.target = target ? target : flag ? 100 : 0;
      this.flag = flag || -1;
      this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
      this.si = setInterval(function(){fadeEffect.tween()}, 20);
    },
    tween:function(){
      if(this.alpha == this.target){
        clearInterval(this.si);
      }
     else{
       var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
       this.elem.style.opacity = value / 100;
       this.elem.style.filter = 'alpha(opacity=' + value + ')';
       this.alpha = value
    }
  }
}
}();
window.onload=function(){
  var fadein=document.getElementById("fadein");
  var fadeout=document.getElementById("fadeout");
   
  fadein.onclick=function(){fadeEffect.init('fade', 1)}
  fadeout.onclick=function(){fadeEffect.init('fade', 0)}
}
</script>
</head>
<body>
<div id="wrapper">
  <div id="fade">犀牛前端部落欢迎你</div>
  <div id="buttons">
    <div class="button" id="fadein">点击淡入</div>
    <div class="button floatright" id="fadeout">点击淡出</div>
  </div>
</div>
</body>
</html>

JavaScript淡入淡出效果,这样的场景在实际项目中还是用的比较多的,关于JavaScript淡入淡出效果就介绍到这了。

回复

我来回复
  • 暂无回复内容