Skip to main content

多行文本擦除效果

源码
import styled from 'styled-components'
import { useColorMode } from '@docusaurus/theme-common'

const DivWrapper = styled.div`
position: relative;

.eraser {
position: absolute;
left: 0;
top: 0;
.text {
--p: 0%;
color: transparent; // 文字只起撑开作用
background: linear-gradient(
to right,
${props => (props.isDarkTheme ? '#1b1b1d00' : '#fff0')} var(--p),
${props => (props.isDarkTheme ? '#1b1b1d' : '#fff')} calc(var(--p) + 100px)
);
animation: erase 5s forwards;
}

/* 自定义一个CSS属性 */
@property --p {
syntax: '<percentage>';
initial-value: 0%;
inherits: false;
}

/* 动画 */
@keyframes erase {
to {
--p: 100%;
}
}
}
`

export default function () {
const { colorMode } = useColorMode()
const isDarkTheme = colorMode === 'dark'
return (
<DivWrapper isDarkTheme={isDarkTheme}>
<p>
Life is too short to spend time with people who suck the happiness out of you. If someone wants you in their life, they’ll make room for you.
You shouldn’t have to fight for a spot. Never, ever insist yourself to someone who continuously overlooks your worth. And remember, it’s not
the people that stand by your side when you’re at your best, but the ones who stand beside you when you’re at your worst that are your true
friends.
</p>
<p className="eraser">
<span className="text">
Life is too short to spend time with people who suck the happiness out of you. If someone wants you in their life, they’ll make room for
you. You shouldn’t have to fight for a spot. Never, ever insist yourself to someone who continuously overlooks your worth. And remember,
it’s not the people that stand by your side when you’re at your best, but the ones who stand beside you when you’re at your worst that are
your true friends.
</span>
</p>
</DivWrapper>
)
}

实现上面效果关键点如下:

  1. 需要纯色背景
  2. 需要复制原文本,可以用 js 添加
  3. 需要行盒元素设置渐变,如上面源码的 span
  4. 用变量定义渐变位置,用动画改变变量值,此处必须用 CSS3 的 Houdini API 中的 @property 将变量 --p 注册成 CSS 属性,因为动画生效前提是必须要是一个数值类的 CSS 属性(而不是 CSS 变量)