Циклический эффект пишущей машинки CSS и изменение текста

Мне нужно прокрутить эффект пишущей машинки CSS и изменить текст для каждого цикла. Вот код, который я использую для эффекта пишущей машинки. Я предполагаю, что мне нужно использовать javascript, но я не уверен, как это сделать. Любые идеи о том, как я могу это сделать?

.typewriter h1 {
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation: 
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}


body {
  background: #333;
  color: #fff;
  font-family: monospace;
  padding-top: 5em;
  display: flex;
  justify-content: center;
}

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation: 
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: blue; }
}
<div class="typewriter">
  <h1>The cat and the hat.</h1>
</div>

}


person Kevin Shiflett    schedule 15.03.2017    source источник
comment
Просто примечание: ваш код скопирован с: css-tricks.com/snippets/ css/эффект пишущей машинки. Упоминание источника — это хорошо. :-)   -  person JoostS    schedule 12.09.2019


Ответы (3)


Да, вам понадобится скрипт, по крайней мере, для обнаружения конца анимации. Затем, чтобы обновить html-контент, вы можете сохранить все сообщения для отображения в массиве и прокрутить его. Затем вам нужно отрегулировать скорость в зависимости от длины отображаемого текста.

var messages=["message1","message2  message2 message2","message3 message3"];
var rank=0;

// Code for Chrome, Safari and Opera
document.getElementById("myTypewriter").addEventListener("webkitAnimationEnd", changeTxt);

// Standard syntax
document.getElementById("myTypewriter").addEventListener("animationend", changeTxt);

function changeTxt(e){
  _h1 = this.getElementsByTagName("h1")[0];
  _h1.style.webkitAnimation = 'none'; // set element animation to none
   setTimeout(function() { // you surely want a delay before the next message appears
      _h1.innerHTML=messages[rank];
      var speed =3.5*messages[rank].length/20; // adjust the speed (3.5 is the original speed, 20 is the original string length
      _h1.style.webkitAnimation = 'typing '+speed+'s steps(40, end), blink-caret .75s step-end infinite'; //  switch to the original set of animation      
      (rank===messages.length-1)?rank=0:rank++; // if you have displayed the last message from the array, go back to the first one, else go to next message
    }, 1000);
}
.typewriter h1 {
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation: 
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}


body {
  background: #333;
  color: #fff;
  font-family: monospace;
  padding-top: 5em;
  display: flex;
  justify-content: center;
}


/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: blue; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="typewriter" id="myTypewriter">
  <h1>The cat and the hat.</h1>
</div>

также проверьте другой синтаксис https://www.w3schools.com/jsref/prop_style_animation.asp< /а>

person scraaappy    schedule 15.03.2017

Это можно сделать с помощью jQuery (или JavaSript, если хотите). Просто подождите, пока анимация не завершится, а затем замените содержащий HTML.

setTimeout(function () {
  $(".typewriter").html("<h1>This is a really cool string</h1>")
},3500);
.typewriter h1 {
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation: 
  typing 3.5s steps(40, end),
  blink-caret .75s step-end infinite;
}


body {
  background: #333;
  color: #fff;
  font-family: monospace;
  padding-top: 5em;
  display: flex;
  justify-content: center;
}

/* DEMO-SPECIFIC STYLES */
.typewriter h1 {
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation: 
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: blue; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="typewriter">
  <h1>The cat and the hat.</h1>
</div>

person Neil    schedule 15.03.2017

Для этого вам НЕ НУЖЕН JavaScript.

Не обманывайте себя. Это можно сделать только с помощью CSS, см. https://stackoverflow.com/a/57887588/2397550 рабочий пример. Вы можете разделить анимацию CSS на несколько отдельных и выполнять их друг за другом с помощью animation-delay.

(Другой) недостаток вашего решения заключается в том, что для него требуется моноширинный шрифт, что является ограничением, которое я бы не хотел иметь.

person JoostS    schedule 12.09.2019