Javascript перебирает массив строк и добавляет к каждому эффект ввода / удаления, выполняя одну за другой - PullRequest
0 голосов
/ 02 октября 2018

Компонент, который я создаю, предназначен для ввода, а затем удаления списка строк.В настоящее время у меня есть эффект ввода / удаления.Тем не менее, я не могу заставить цикл работать правильно.

Желаемый эффект - набрать + нетипизировать первую строку, ТОГДА вторую, ТОГДА третью и т. Д.

var pos = 0
var speed = 50
var speed2 = 100
var str = document.getElementById('str')
var i

var messages = [
    "Cyber Security",
    "Vulnerability Assessments",
    "Program Management",
    "Compliance Management"
]

messages.forEach(function (message) {

    function type() {
        console.log('Type ' + pos)
        if (pos < message.length) {
            str.innerText += message.charAt(pos)
            pos++
            setTimeout(type, speed) //call this fn again to type letters
        } else {
            setTimeout(erase, speed2)
        }
    }

    type(type, speed)

    //erase fn
    function erase() {
        console.log('Erase ' + pos)
        if (pos >= 0) {
            var temp = message.substring(0, pos)
            str.innerText = temp
            pos--
            setTimeout(erase, speed2)
        }
    }
})
<section class="hollow-hero-21">
    <div class="flex-container">
        <h1>
            Innovative Solutions
            <br>for
            <span id="str"></span>
        </h1>
        <hr>
        <p>This is filler content. The text in this area will be replaced when copy for the site becomes available. This is filler content. The text in this area will be replaced when copy for the site becomes available.</p>
        <a href="#">Learn More</a>
    </div>
</section>

1 Ответ

0 голосов
/ 02 октября 2018

В настоящее время у вас есть проблема с тем, что вы запускаете все операции набора текста и последующего последовательного удаления одновременно из-за цикла messages.forEach.

Нет необходимости в этом цикле, так как вы хотитеподождите, пока каждое слово не будет набрано и удалено.Поэтому вам нужно будет запомнить индекс вашего текущего сообщения, пока вы его набираете и удаляете, а затем обновляете его после удаления последнего слова.

Я изменил ваш скрипт так, чтобы цикл имелбыл удален, и на данный момент существует только 1 действие с битовым флагом, говорящим о isRemoving.Лично я предпочел бы сделать это с setInterval, но чтобы не изменить желаемое поведение, я добавил вместо него setTimeout.

Эта версия будет работать бесконечно, как после удаления последнего слова из массива., он вернется к первому сообщению в вашем массиве.

var speed = 50;
var speed2 = 100;
var str = document.getElementById('str');
var i = 0;
var isRemoving = false;

var messages = [
    "Cyber Security",
    "Vulnerability Assessments",
    "Program Management",
    "Compliance Management"
]

function action() {
  if (isRemoving) {
    if (str.innerText.length > 0) {
      str.innerText = str.innerText.substr(0, str.innerHTML.length - 1);
      setTimeout( action, speed2 );
      return;
    }
    isRemoving = false;
    i++;
    if (i >= messages.length) {
      i = 0;
    }
    setTimeout( action, speed );
    return;
  }
  var message = messages[i];
  str.innerText = message.substr(0, str.innerHTML.length + 1);
  if (str.innerText.length === message.length) {
    isRemoving = true;
  }
  setTimeout( action, isRemoving ? speed2 : speed );
}

setTimeout( action, speed ) ;
<section class="hollow-hero-21">
    <div class="flex-container">
        <h1>
            Innovative Solutions
            <br>for
            <span id="str"></span>
        </h1>
        <hr>
        <p>This is filler content. The text in this area will be replaced when copy for the site becomes available. This is filler content. The text in this area will be replaced when copy for the site becomes available.</p>
        <a href="#">Learn More</a>
    </div>
</section>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...