Хотите получить эффект пишущей машинки, работающий над вашим портфолио, чтобы произвести потрясающее впечатление на новых посетителей. Тогда вы в правильном посте. Сегодня я точно покажу, как заставить это работать. Итак, это то, чего мы пытаемся достичь сегодня.

Чтобы увидеть, как работает эта штука, вы можете посетить мой сайт-портфолио по адресу https://abhishek.sairyonodevs.in. Ссылка на весь исходный код будет доступна в конце этого поста.

Итак, приступим.

Во-первых, нам нужно настроить наш html.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>. . .</title>
    </head>
    <body>
     .
     .
    </body>
</html>

Теперь давайте пишущей машинке эффект стиля заголовка внутри тела html. Наши предложения будут параметрами тега div, а фактическое текстовое содержимое div будет пустым. Затем мы получим эти предложения с помощью javascript и вставим их в пустой тег, который мы туда поместим.

<h1>
  <div class="typewrite" data-period="1000" data-type='[ "Hi, I&#39m &#128526; Abhishek Adhikari.", "&#128514; You just copied this code, right?", "No worries.", "👨‍💻 Just go through the code you will get it.", "Jai Hind !!! " ]'>
    <span class="wrap"></span>
  </div>
</h1>

Теперь мы получим наш код javascript для извлечения предложений из html и передачи их в пустой тег.

window.onload = function() {
    var elements = document.getElementsByClassName('typewrite');
    for (var i=0; i<elements.length; i++) {
        var toRotate = elements[i].getAttribute('data-type');
        var period = elements[i].getAttribute('data-period');
        if (toRotate) {
          new TxtType(elements[i], JSON.parse(toRotate), period);
        }
    }
};

Теперь мы создадим функцию TxtType для эффекта печати.

var TxtType = function(el, toRotate, period) {
    this.toRotate = toRotate;
    this.el = el;
    this.loopNum = 0;
    this.period = parseInt(period, 10) || 2000;
    this.txt = '';
    this.tick();
    this.isDeleting = false;
};

TxtType.prototype.tick = function() {
    var i = this.loopNum % this.toRotate.length;
    var fullTxt = this.toRotate[i];

    if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
    } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
    }

    this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';

    var that = this;
    var delta = 200 - Math.random() * 100;

    if (this.isDeleting) { delta /= 2; }

    if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
    } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum++;
    delta = 500;
    }

    setTimeout(function() {
    that.tick();
    }, delta);
};

И чтобы получить курсор, мы добавим правую границу к тегу, вводя css при загрузке javascript.

var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".typewrite > .wrap { border-right: 0.10em solid #fff}";
document.body.appendChild(css);

К этому времени машинка уже работает. Но мы добавим немного CSS, чтобы он выглядел лучше. Собрав все это вместе, код становится.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Typewriter-effect</title>
        <style>
            body {
                width: 100%;
                height: 100%;
                background-color: rgb(255, 94, 0);
                overflow: hidden; /* to hide scroll bars nothing to do with type-writer */
                text-align: center;
            }
            h1 {
                padding: 20% 0;
                color: white;
            }
        </style>
    </head>
    <body>
        <h1>
            <div class="typewrite" data-period="1000" data-type='[ "Hi, I&#39m &#128526; Abhishek Adhikari.", "&#128514; You just copied this code, right?", "No worries.", "👨‍💻 Just go through the code you will get it.", "Jai Hind !!! " ]'>
              <span class="wrap"></span>
            </div>
        </h1>
        <script>
var TxtType = function(el, toRotate, period) {
    this.toRotate = toRotate;
    this.el = el;
    this.loopNum = 0;
    this.period = parseInt(period, 10) || 2000;
    this.txt = '';
    this.tick();
    this.isDeleting = false;
};

TxtType.prototype.tick = function() {
    var i = this.loopNum % this.toRotate.length;
    var fullTxt = this.toRotate[i];

    if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
    } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
    }

    this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>'; //the text for each step is inserted inside the <span>

    var that = this;
    var delta = 200 - Math.random() * 100;

    if (this.isDeleting) { delta /= 2; }

    if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
    } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum++;
    delta = 500;
    }

    setTimeout(function() {
    that.tick();
    }, delta);
};

window.onload = function() {
    var elements = document.getElementsByClassName('typewrite'); //the typewrite tag from html is linked to elements
    for (var i=0; i<elements.length; i++) {
        var toRotate = elements[i].getAttribute('data-type'); //all the sentences are stored here
        var period = elements[i].getAttribute('data-period');
        if (toRotate) {
          new TxtType(elements[i], JSON.parse(toRotate), period);
        }
    }
    //once this function starts working
    //the css for .wrap <span> is injected to the DOM
    var css = document.createElement("style");
    css.type = "text/css";
    css.innerHTML = ".typewrite > .wrap { border-right: 0.10em solid #fff}";
    document.body.appendChild(css);
};
        </script>
    </body>
</html>

Надеюсь, вам понравилось читать этот пост, и вы заработали свой собственный эффект пишущей машинки. Вот что мы создали сегодня
https://abhishekadhikari23.github.io/typewriter-effect/.

Вот репозиторий этого руководства.