淡入淡出是一种常见的视觉过渡效果,广泛应用于网页开发、移动应用和多媒体处理中。下面我将详细介绍各种实现方法。
淡入(Fade In)是指元素从完全透明逐渐变为完全不透明的过程;淡出(Fade Out)则是相反的过程,从完全不透明逐渐变为完全透明。
/* 淡入动画 */
.fade-in {
animation: fadeIn 1s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* 淡出动画 */
.fade-out {
animation: fadeOut 1s;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
// 淡入函数
function fadeIn(element, duration = 1000) {
element.style.opacity = 0;
let start = null;
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const opacity = Math.min(progress / duration, 1);
element.style.opacity = opacity;
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
// 淡出函数
function fadeOut(element, duration = 1000) {
element.style.opacity = 1;
let start = null;
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
const opacity = Math.max(1 - progress / duration, 0);
element.style.opacity = opacity;
if (progress < duration) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
// 淡入
$("#element").fadeIn(1000);
// 淡出
$("#element").fadeOut(1000);
import React, { useState, useEffect } from 'react';
function FadeComponent({ show, children }) {
const [opacity, setOpacity] = useState(show ? 1 : 0);
useEffect(() => {
setOpacity(show ? 1 : 0);
}, [show]);
return (
<div style={{
opacity: opacity,
transition: 'opacity 1s ease-in-out'
}}>
{children}
</div>
);
}
<template>
<transition name="fade">
<div v-if="show">内容</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
原因:可能使用了setTimeout而不是requestAnimationFrame 解决:改用requestAnimationFrame或CSS动画
原因:opacity为0时元素仍在DOM中 解决:淡出完成后移除元素或设置display:none
function fadeOutAndRemove(element, duration) {
fadeOut(element, duration);
setTimeout(() => {
element.style.display = 'none';
}, duration);
}
原因:过多元素同时动画或复杂布局 解决:
.fade-element {
will-change: opacity;
}
.fade-in {
transition: opacity 1s cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes fadeAndSlide {
0% {
opacity: 0;
transform: translateY(20px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
function crossFade(elementOut, elementIn, duration) {
fadeOut(elementOut, duration);
fadeIn(elementIn, duration);
}
希望这些方法能帮助你实现所需的淡入淡出效果。根据具体场景选择最适合的实现方式。
没有搜到相关的文章