使用纯JavaScript实现淡入淡出效果,主要通过setInterval
定时器逐步改变元素的透明度(opacity)来实现。这种方法不依赖jQuery或CSS动画,完全通过JavaScript控制。
setInterval
创建定时器style.opacity
属性function fadeIn(element, duration = 400) {
let opacity = 0;
const interval = 16; // 大约60fps
const increment = interval / duration;
element.style.opacity = opacity;
element.style.display = 'block'; // 确保元素可见
const timer = setInterval(function() {
opacity += increment;
element.style.opacity = opacity;
if (opacity >= 1) {
clearInterval(timer);
element.style.opacity = 1;
}
}, interval);
}
function fadeOut(element, duration = 400) {
let opacity = 1;
const interval = 16; // 大约60fps
const decrement = interval / duration;
const timer = setInterval(function() {
opacity -= decrement;
element.style.opacity = opacity;
if (opacity <= 0) {
clearInterval(timer);
element.style.opacity = 0;
element.style.display = 'none'; // 可选:淡出后隐藏元素
}
}, interval);
}
<div id="myElement" style="width:100px; height:100px; background:blue; display:none;"></div>
<button onclick="fadeIn(document.getElementById('myElement'))">淡入</button>
<button onclick="fadeOut(document.getElementById('myElement'))">淡出</button>
可以添加回调函数,在动画结束时执行特定操作:
function fadeIn(element, duration = 400, callback) {
let opacity = 0;
const interval = 16;
const increment = interval / duration;
element.style.opacity = opacity;
element.style.display = 'block';
const timer = setInterval(function() {
opacity += increment;
element.style.opacity = opacity;
if (opacity >= 1) {
clearInterval(timer);
element.style.opacity = 1;
if (typeof callback === 'function') {
callback();
}
}
}, interval);
}
虽然setInterval
可以实现淡入淡出效果,但现代浏览器中更推荐使用:
但这些方法不属于纯JavaScript实现,所以不在本问题的讨论范围内。
没有搜到相关的文章