原生JavaScript实现元素渐隐与渐显效果

作者:像素猫

时间:2026-10-28

浏览:644

本文介绍如何使用原生JavaScript实现元素的渐隐与渐显动画。核心原理是通过定时器动态修改元素的opacity属性,并针对IE浏览器使用filter:alpha滤镜兼容处理。文章提供了完整的HTML结构与JS函数代码,支持指定元素ID及show/hide两种模式,适用于简单的图片淡入淡出场景。

文章目录

原生JavaScript实现元素渐隐与渐显效果

经常看到网页中图片以渐变方式显示,这里尝试自行编写一个实现方案。


其核心原理非常直接,即通过动态修改元素的CSS透明度属性来实现视觉上的淡入淡出效果。


在线预览效果地址:http://jsfiddle.net/dtdxrk/BHUp9/embedded/result/


具体实现代码如下:

 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>原生Js元素渐隐/渐显方法</title>
</head>
<body>
<button id="show">渐显</button>
<button id="hiden">渐隐</button>
<img src="http://images.cnitblog.com/blog/150659/201306/20171658-303d375a1ec740e29a567b269d6297f1.jpg" id="img">
<script type="text/javascript">
function alphaPlay(obj,method){ //method有两个值show或hiden
var n = (method == "show") ? 0 : 100,
ie = (window.ActiveXObject) ? true : false;
var time = setInterval(function(){
if(method == "show"){
if(n < 100){
n+=10;
if(ie){
obj.style.cssText = "filter:alpha(opacity="+n+")";
}else{
(n==100) ? obj.style.opacity = 1 : obj.style.opacity = "0."+n;
} 
}else{
clearTimeout(time);
} 
}else{
if(n > 0){
n-=10;
if(ie){
obj.style.cssText = "filter:alpha(opacity="+n+")";
}else{
obj.style.opacity = "0."+n;
} 
}else{
clearTimeout(time);
} 
} 
},30);
} 
var img = document.getElementById("img");
document.getElementById("show").onclick = function(){
alphaPlay(img,"show");
} 
document.getElementById("hiden").onclick = function(){
alphaPlay(img,"hiden");
} 
</script>
</body>
</html>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章