JavaScript 中的淡入 Div
CSS 动画可以帮助你制作从一个 CSS 样式位置到另一个位置的动画过渡。
动画包含组件、描述 CSS 动画的样式,以及暗示动画样式的开始和结束状态以及参考点之间的所有状态的关键帧序列。
在今天的文章中,我们将学习使用纯 JavaScript 淡入和淡出 div。
JavaScript 中的淡入 Div
CSS fade
过渡是一种元素(例如文本、图像或背景)在页面上逐渐出现或消失的效果。要创建这些效果,请使用 CSS 中的过渡或动画属性。
在 JavaScript 中创建淡入函数的步骤
让我们用 Hello World!
创建一个 div 文本。每次页面加载时,都会播放此动画,并且页面似乎会淡入。
可以在设置的间隔内设置渐变时间。
<div id="fadeEl" class="fadeElClass"
onclick="fadeIn()">
Hello World!
</div>
.fadeElClass {
width: 200px;
height: 20px;
text-align: center;
background: red;
}
function fadeIn() {
const element = document.getElementById('fadeEl');
console.log(element.style);
// Initilize the opacity with 0.1
let initOpacity = 0.1;
element.style.display = 'block';
// Update the opacity with 0.1 every 10 milliseconds
const timer = setInterval(function() {
if (initOpacity >= 1) {
clearInterval(timer);
}
element.style.opacity = initOpacity;
element.style.filter = 'alpha(opacity=' + initOpacity * 100 + ')';
initOpacity += initOpacity * 0.1;
}, 500);
}
fadeIn()
尝试在任何浏览器中运行上述代码;它会在 hello world
文本中从 0.1 淡化到 1 不透明度。
输出:
淡入前:
淡入后:
此处演示
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。