如何在单一功能的单页中实现多类型元素

How to implement multi typed elements in single page with single function

我正在尝试在 typed.js 中共享相同 class 的页面上的两个 div(使用 stringElements),目前只有第一个出现起作用。

在这里,可以用不同的 class 来实现 2 个不同的函数。但是,我想使用具有相同 class.

的单一功能

在这里向您展示我正在尝试做的事情。 https://jsfiddle.net/xbofduaz/

正确的方法是什么。

var typed1 = new Typed('.typed', {
  stringsElement: '.typed-strings',
  loop: true,
  typeSpeed: 50,
  backSpeed: 20,
  backDelay: 1700,
  showCursor: false,
});

HTML

<div class="wrap">
  <h1>TypedJS on multiple identical stringElements on the page</h1>

  <div class="typed-strings">
    <p>Ice cream</p>
    <p>Moog synth</p>
    <p>Holidays in space</p>
  </div>
  <span class="typed"></span>

  <p> Some other stuff on the page goes on, until we uncounter the exact same typed strings, that I also want to animate (and tarket thanks to a class). To note that both of these similar blocks come from the database, I'm unable to duplicate them to change their class or id, I need them to be exactly the same, and both be animated. </p>

  <div class="typed-strings">
    <p>Ice cream</p>
    <p>Moog synth</p>
    <p>Holidays in space</p>
  </div>
  <span class="typed"></span> </div>

可以看到在typedjsload method中使用了document.querySelector()。所以不能构造多个元素。尝试使用 querySelectorAll()

document.querySelectorAll('.typed').forEach(function(el) {
    new Typed(el, {
    stringsElement: el.previousElementSibling,
    loop: true,
    typeSpeed: 50,
    backSpeed: 20,
    backDelay: 1700,
    showCursor: false,
  })
});

工作演示

https://jsfiddle.net/ebjzmLur/