100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 利用css动画实现打字机效果

利用css动画实现打字机效果

时间:2019-05-03 01:37:55

相关推荐

利用css动画实现打字机效果

简言

通过使用css的animation(动画属性)实现文字显示的打字机效果。

单行

思路

实现步骤:

将文本框属性设置为等宽字体,计算文本框的字数,设置文字大小、相对布局等。将文本框隐藏,通过动画改变文本框宽度,动画速度曲线使用css内置函数steps()变成步长动画,然后将动画模式设置为forwards,保留动画最后一帧样式。使用伪元素after,设置边框属性和绝对布局,模拟光标;再使用动画实现若隐若现效果。

代码

这里是用改变宽度和步长动画搭配实现效果。宽度单位是em,数值根据这行文字的多少来计算。

<template><div class="container"><div class="text__box one">这是一个打字机效果1!!!</div><!-- <div class="text__box two">这是一个打字机效果2!!!</div><div class="text__box three">这是一个打字机效果3!!!</div><div class="text__box four">这是一个打字机效果4!!!</div> --></div></template><script lang="ts" setup>import {reactive, ref, toRefs, onBeforeMount, onMounted, computed } from "vue";</script><style lang="scss" scoped>.container {position: relative;margin-top: 100px;margin-left: 100px;}.text__box {position: relative;overflow: hidden;width: 0;font-size: 32px;line-height: 34px;font-family: "Courier New", Courier, monospace;white-space: nowrap;animation: width 2s steps(13) forwards;&::after {content: "";position: absolute;right: 0px;height: 32px;border-right: 1px solid #000;animation: showInfinite 0.5s infinite both;}}.one {animation-delay: 0s;}@keyframes width {0% {width: 0;}100% {width: 13em; // 单位em,表示一个字体的宽度}}@keyframes showInfinite {0% {opacity: 1;}100% {opacity: 0;}}</style>

效果

多行

思路

多行打字机实现思路是在单行的基础上进行的。

利用动画延迟属性,来实现单行实现过渡到多行实现的效果。

需要注意的是光标的处理,是最后一行光标才可以无限动画,其他行可以指定光标动画执行次数。

代码

<template><div class="container"><div class="text__box one">这是一个打字机效果1!!!</div><div class="text__box two">这是一个打字机效果2!!!</div><div class="text__box three">这是一个打字机效果3!!!</div><div class="text__box four">这是一个打字机效果4!!!</div></div></template><script lang="ts" setup>import {reactive, ref, toRefs, onBeforeMount, onMounted, computed } from "vue";</script><style lang="scss" scoped>.container {position: relative;margin-top: 100px;margin-left: 100px;}.text__box {position: relative;overflow: hidden;width: 0;font-size: 32px;line-height: 34px;font-family: "Courier New", Courier, monospace;white-space: nowrap;animation: width 2s steps(13) forwards;&::after {content: "";position: absolute;right: 0px;height: 32px;border-right: 1px solid #000;animation: showInfinite 0.5s 5 both;//执行5次}}.one {animation-delay: 0s;}.two {animation-delay: 2s;&::after {animation-delay: 2s;}}.three {animation-delay: 4s;&::after {animation-delay: 4s;}}.four {animation-delay: 6s;&::after {animation-delay: 6s;animation: showInfinite 0.5s infinite both;}}@keyframes width {0% {width: 0;}100% {width: 13em; // 单位em,表示一个字体的宽度}}@keyframes showInfinite {0% {opacity: 1;}100% {opacity: 0;}}</style>

效果

结语

这里主要运用的是步长动画,另外要注意一行文字的长度,然后根据长度,改变步长。多行打字机也是如此,一般最后一行需要特殊处理。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。