光标自动打字的效果

在这个示例中,我们首先在HTML中定义了一个div元素,并在其中添加了一个p元素以及伪类,分别用于显示打印的文本和光标。在CSS中,我们设置了打印文本和光标的样式,并定义了光标闪烁的动画。

在Javascript中,我们首先获取了打印文本元素,并定义了要打印的文本和每个字符打印的时间间隔和光标闪烁的时间间隔。

接着,我们定义了一个type函数,用于实现打印文本和移动光标的效果。在该函数中,我们首先计算出应该打印的文本,并更新显示的文本。然后判断是否打印完所有文本,如果没有则继续打印。

最后,在全局作用域中,我们定义了一个typingIndex变量用于记录已经打印的字符数,并计算出每个字符的,代码如下:

HTML

    <div id="typing-container">
        <p id="typing"></p>
    </div>

CSS
 


        #typing {
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            font-size: 24px;
            line-height: 1.5;
        }
        #typing::after{
            content: '|';
            animation: blink 0.8s infinite;
            padding-left: 5px;
        }

        @keyframes blink {
            50% {
                opacity: 0;
            }
        }

JS

    const typingElement = document.getElementById("typing");
    const text = "This is an example of typing animation.";
    const typingDelay = 50; // 每个字符打印的时间间隔
    const cursorDelay = 500; // 光标闪烁的时间间隔

    function type() {
        // 计算出应该打印的文本
        const currentText = text.slice(0, typingIndex);

        // 更新显示的文本和光标位置
        typingElement.textContent = currentText;

        // 如果还没打印完所有文本,则继续打印
        if (typingIndex < text.length) {
            typingIndex++;
            setTimeout(type, typingDelay);
        }
    }

    let typingIndex = 0;
    const charWidth = typingElement.getBoundingClientRect().width / text.length;

    // 等待一段时间,让用户有时间看到光标
    setTimeout(type, cursorDelay);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值