Эффект печати для списка строк. Нужна помощь в исправлении порядка событий - PullRequest
0 голосов
/ 30 октября 2018

Мне нужен следующий код для ввода / нетипизации каждой строки, по одной в том порядке, в котором они перечислены. В настоящее время он выполняется, но i ++ запускает слишком много раз в цикле и нарушает порядок событий. Помогите исправить итерации, чтобы любое количество строк можно было набирать / не печатать по порядку.

<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>



$(function() {

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

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

  function action() {
    console.log('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, 500 );
      return;
    }

    var message = messages[i];

    str.innerText = message.substr(0, str.innerHTML.length + 1);
    if (str.innerText.length === message.length) {
      setTimeout(function() {
        isRemoving = true;
        console.log(isRemoving)
      }, 2000)
    }
    setTimeout( action, isRemoving ? speed2 : speed );
  }

  setTimeout( action, speed ) ;
})

Ответы [ 3 ]

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

Если вы не хотите переделывать весь свой код, вы можете позвонить на i++; только тогда, когда сообщение будет полностью набрано (str.innerText.length === message.length)

$(function() {

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

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

  function action() {
    console.log('Action')

    if (isRemoving) {
      if (str.innerText.length > 0) {
        str.innerText = str.innerText.substr(0, str.innerHTML.length - 1);
        setTimeout(action, speed2);
        return;
      }
      isRemoving = false;

      setTimeout(function() {
        action();
      }, 500);
      return;
    } else {

      var message = messages[i];
      console.log(i);
      str.innerText = message.substr(0, str.innerHTML.length + 1);
      if (str.innerText.length === message.length) {

        i++;
        if (i === messages.length) {
          i = 0;
        }

        setTimeout(function() {
          isRemoving = true;
          setTimeout(action, isRemoving ? speed2 : speed);
        }, 2000)

      } else {
        setTimeout(action, isRemoving ? speed2 : speed);
      }
    }
  }

  setTimeout(action, speed);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
0 голосов
/ 30 октября 2018

$(function() {

    var speed = 200;
    var speed2 = 50;
    var str = document.getElementById('str');
    var index =0;
    var isRemoving = false;
  
    var messages = [
      "Cyber Security...",
      "Vulnerability Assessments...",
      "Program Management...",
      "Compliance Management..."
    ] 
   
    
    function getIndex(index1){  
   
    if(index1===messages.length){
        return(0)
    }
    else{
        return(index1);
    }
}
    function action(){  
     
    if(isRemoving){  
        str.innerText = str.innerText.substr(0,str.innerHTML.length - 1);
        if(str.innerHTML.length===0) {
            index=getIndex(index+1);
            isRemoving=false;        
        }      
        setTimeout( action, speed2 );        
    }
    else{      
        str.innerText = messages[index].substr(0, str.innerHTML.length + 1);
        if(str.innerHTML.length===messages[index].length){
           
            isRemoving=true; 
        }         
        setTimeout( action, speed );
       }  
       
    }    
  
    setTimeout( action, speed ) ;
  });
  <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>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
0 голосов
/ 30 октября 2018

Я бы хотел, чтобы в вашем коде было только одно вхождение setTimeout. Сделайте все остальное динамическим и передайте состояние каждому следующему вызову action (используйте для этого bind).

Вот как это будет выглядеть:

var str = document.getElementById('str');

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

function action(idx, len, dir) {
    str.textContent = messages[idx].slice(0, len);
    if (len % messages[idx].length == 0) dir = -dir; // Change direction
    setTimeout(
        action.bind(null, (idx+(len==0)) % messages.length, len+dir, dir), 
        len == messages[idx].length ? 2000 : dir < 0 ? 50 : 200 // Delay
    );
}

action(0, 1, 1); // Not really useful to have setTimeout here. Just call it.
<div class="flex-container">
    <h1>Innovative Solutions
        <br>for
        <span id="str"></span>
    </h1>
    <hr>
    <p>This is filler content.</p>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...