首页 > 解决方案 > 如何多次使用自动文本输入功能?(JavaScript)

问题描述

美好的一天,你们会的。

我有一个快速的问题。在我开始之前,我对 JavaScript 的了解并不多。

下面是我在 JavaScript 中使用的自动文本输入功能。要使用它,我需要向我想要动画的元素添加两个类,“type-js”和“text-js”。但是我想在不同的文本上多次使用它。因为当我将它添加到两个元素时,它会记录第一个文本并在第二个文本上使用它。

这是代码:

function autoType(elementClass, typingSpeed){
  var thhis = $(elementClass);
  thhis.css({
    "position": "relative",
    "display": "inline-block"
  });
  thhis.prepend('<div class="cursor" style="right: initial; left:0;"></div>');
  thhis = thhis.find(".text-js");
  var text = thhis.text().trim().split('');
  var amntOfChars = text.length;
  var newString = "";
  thhis.text("|");
  setTimeout(function(){
    thhis.css("opacity",1);
    thhis.prev().removeAttr("style");
    thhis.text("");
    for(var i = 0; i < amntOfChars; i++){
      (function(i,char){
        setTimeout(function() {        
          newString += char;
          thhis.text(newString);
        },i*typingSpeed);
      })(i+1,text[i]);
    }
  },1500);
}

$(document).ready(function(){
  // Now to start autoTyping just call the autoType function with the 
  // class of outer div
  // The second paramter is the speed between each letter is typed.   
  autoType(".type-js",200);
});

这是一个例子。

正如您在上面的 GIF 中看到的那样。我正在使用自动文本输入功能两次。在下面的元素和 GIF 中显示的元素中。但它将两个文本都记录到变量中。我怎样才能让它多次重复使用,而不将它记录到变量中并在所有元素上显示它?我希望它单独显示。就像上面的 GIF 一样,它应该只显示“市场部门”,而在远低于该部门的 DIV 中,它应该只显示“公司”。不是都。

如果这篇文章听起来很荒谬,我很抱歉。我尽力详细说明。

谢谢!祝你有愉快的一天。

标签: javascripthtmlfunction

解决方案


如果类中有多个元素,您的选择器将返回多个元素type-js...
所以在each().
见例子。

function autoType(elementClass, typingSpeed){
  // Run on each item that has the class.
  $(elementClass).each(function(){
    var thhis = $(this);
    thhis.css({
      "position": "relative",
      "display": "inline-block"
    });
    thhis.prepend('<div class="cursor" style="right: initial; left:0;"></div>');
    thhis = thhis.find(".text-js");
    var text = thhis.text().trim().split('');
    var amntOfChars = text.length;
    var newString = "";
    thhis.text("|");
    setTimeout(function(){
      thhis.css("opacity",1);
      thhis.prev().removeAttr("style");
      thhis.text("");
      for(var i = 0; i < amntOfChars; i++){
        (function(i,char){
          setTimeout(function() {        
            newString += char;
            thhis.text(newString);
          },i*typingSpeed);
        })(i+1,text[i]);
      }
    },1500);
  })
}

$(document).ready(function(){
  // Now to start autoTyping just call the autoType function with the 
  // class of outer div
  // The second paramter is the speed between each letter is typed.   
  autoType(".type-js",200);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="type-js">
  <div class="text-js">
  testing
  </div>
</div>
<br/>
<div class="type-js">
  <div class="text-js">
  testing again
  </div>
</div>


推荐阅读