所以我一直在玩一个项目,其中包括一个随机引用生成器,我希望当生成器加载新引用时,将其与简单的 typewriter 风格的动画结合起来.

问题是我对javascript知之甚少,而且基本上不知道我在做什么,这使得实现其他人的类似但不完全是it的解决方案变得困难.

该代码的基本内容如下;

const generateQuote = function() {
  const quotes = [{
      quote: "Here's a text",
    },
    {
      quote: "Here's another one",
    },
    {
      quote: "Lorem ipsum bla bla",
    },
    {
      quote: "I can do this all day",
    }
  ];

  let arrayIndex = Math.floor(Math.random() * quotes.length);
  document.getElementById("quotetxt").innerHTML = quotes[arrayIndex].quote;
}

window.onload = function loadquote() {
  generateQuote();
  document.getElementById("generate").addEventListener('click', generateQuote);
}
<p id="quotetxt"> </p>
<button id="generate">generate</button>

我试着将它与我见过的 typewriter 效果脚本(比如W3School上的基本脚本)结合在一起,但我想不出如何让它按我想要的方式工作.我可以让最初加载的引用显示在动画中,或者制作单个文本的动画,但不是像我想的那样从按下按钮的随机数组中进行.

有一次,我设法让报价生成器扰乱了报价中的所有字母,尽管我不知道我是如何做到的,我也没有保留代码.

我看到过一些jquery的 typewriter 效果,但它们似乎都比我所寻找的要先进得多,但如果有一个简单的,你可以推荐,这也是好的.

(我也是一个全新的stackoverflow,我尽我所能遵循的指导方针,但我道歉,如果我错过了什么)

推荐答案

这是我能想到的最简单的

注意,我已经更改了一些代码布局.例如,不需要在每次调用GenerateQuote时创建报价array. 我还清除现有的报价,如果按钮是点击中间的报价. 我将TypeWriter函数放在Load事件处理程序中,因为它需要extElement在作用域中.如果我想将函数移到Load事件处理程序之外,我每次都可以在函数内部获得extElement,但这是一个简单的脚本,所以我保持了实用.

const quotes = [
  { quote: "Here's a text" },
  { quote: "Here's another one" },
  { quote: "Lorem ipsum bla bla" },
  { quote: "I can do this all day" }
];


const generateQuote = () => {
  let arrayIndex = Math.floor(Math.random() * quotes.length);
  return quotes[arrayIndex].quote;
}

window.addEventListener('DOMContentLoaded', () => {
  const textElement = document.getElementById('quotetxt');
  let tId; // timeout handle
  // Typewriter function
  const typeWriter = (text, i = 0) => {
    if (i < text.length) { // while the counter is less than the length of the string
      textElement.innerHTML = text.substring(0, i + 1); // show next letter
      // call the function with the counter at the next letter
      tId = setTimeout(() => typeWriter(text, i + 1), 100); // Adjust speed by changing timeout
    }
  };

  // Event listener for button
  document.getElementById('generate').addEventListener('click', (e) => {
    clearTimeout(tId); // kill running typewriting
    textElement.textContent = "";
    typeWriter(generateQuote());
  });
  typeWriter(generateQuote()); // initialise
});
<p id="quotetxt"> </p>
<button id="generate">generate</button>

Javascript相关问答推荐

如何将特定的字符串类型转换为TypScript中的字符串?

使用Astro和React的动态API

Express.js:以块形式发送响应

Flisk和JS错误:未捕获的Syntax错误:意外的令牌'<'

Vue:ref不会创建react 性属性

传递一个大对象以在Express布局中呈现

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

屏幕右侧屏障上的产卵点""

当id匹配时对属性值求和并使用JavaScript返回结果

连接到游戏的玩家不会在浏览器在线游戏中呈现

检索相加到点的子项

400 bad request error posting through node-fetch

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

为什么客户端没有收到来自服务器的响应消息?

创建以键值对为有效负载的Redux Reducer时,基于键的类型检测

使用auth.js保护API路由的Next.JS,FETCH()不起作用

如何 for each 输入动态设置输入变更值

在VS代码上一次设置多个变量格式

有没有一种直接的方法可以深度嵌套在一个JavaScript对象中?

P5JS-绘制不重叠的圆