首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JavaScript中制作“文字特效”?

如何在JavaScript中制作“文字特效”?
EN

Stack Overflow用户
提问于 2020-07-20 23:02:39
回答 3查看 27关注 0票数 0

这段代码应该每200 MilliSecond键入字符串myText中的一个字母,以类似于type Effect,但它的类型是undefinded而不是letters

代码语言:javascript
运行
复制
var myText = "loremloremloremloremloremloremloremloremloremloremloremlorem",
    myButton = document.getElementById("Button"),
    result = document.getElementById("type"),
    i;
myButton.onclick = function (){
    "use strict";
    setInterval(function(){
        result.textContent += myText[i];
        i++;
    }, 200);
}
代码语言:javascript
运行
复制
<p id="type"></p>
    <button  id="Button">Click!</button>

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-07-20 23:04:11

您缺少i= 0,初始值

票数 1
EN

Stack Overflow用户

发布于 2020-07-20 23:10:17

试一试

代码语言:javascript
运行
复制
result.textContent += myText.substring(i, i+1);

在JS (简短而不精确的解释)中,您试图使用myText[1]访问对象字符串(MyText)的属性"1“。

票数 0
EN

Stack Overflow用户

发布于 2020-07-20 23:14:40

您可以将其封装在一个可重用的函数中,并添加一个检查,以查看已写入了多少字符。

一旦到达字符串的末尾,您就可以取消间隔。

您可以通过在超时后传递附加参数来将附加参数包含在间隔内。

代码语言:javascript
运行
复制
const myText = "loremloremloremloremloremloremloremloremloremloremloremlorem";

document.getElementById('my-button').onclick = (e) => {
  autoType(myText, '#type-1', 50);
  autoType(myText, '#type-2', 100);
}

function autoType(text, target, timeout) {
  target = typeof target === 'string' ?
      document.querySelector(target) : target;
  let intervalId = setInterval((options) => {
    if (options.index >= text.length - 1) {
      clearInterval(intervalId);
    }
    target.textContent += text[options.index];
    options.index++;
  }, timeout, { index: 0 });
}
代码语言:javascript
运行
复制
<p id="type-1"></p>
<p id="type-2"></p>
<button id="my-button">Click!</button>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62998312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档