Как оформить текст из строки JS

#javascript #html #css

#javascript #HTML #css

Вопрос:

Я использую этот эффект пишущей машинки, созданный с помощью JavaScript, HTML и CSS (метод показан ниже), но я хочу сделать еще один шаг вперед. Есть ли способ изменить шрифт каждого вводимого слова? Я искал решения, но, честно говоря, я даже не знаю, что искать. Пожалуйста, дайте мне знать, если это возможно.

 var words = ['Design','Create','Dream', 'Inspire'],
    currentStep = 0,
    textEl = document.querySelector('.change-text'),
    oldWord = '';


setTimeout(changeWord, 2000);

function changeWord() {
  oldWord = textEl.innerHTML;
  
  // check if there is a word atm or not
  if (oldWord.length < 1) {

    if (currentStep !== words.length -1) {
          currentStep   ;
    }else {
      currentStep = 0;
    }
    addNextWord();
  } else {
    setTimeout(deleteWord, 1400);
  }
  
};

function deleteWord() {
  var WordLength = oldWord.length,
      currentWord = textEl.innerHTML,
      currentLength = currentWord.length;
  

  // The word is deleted so, start adding in the new one
  if (currentLength < 1) {
    changeWord();
    return;
  }
  
  // Remove a charachter
  textEl.innerHTML = currentWord.substring(0, currentLength - 1);
  
  setTimeout(deleteWord, 140);
}

function addNextWord() {
  var currentWord = textEl.innerHTML,
      currentLength = currentWord.length,
      nextWord = words[currentStep],
      nextWordLength = nextWord.length;
    
  
  if (currentLength === nextWordLength) {
    changeWord();
    return;
  }
  
  // add a charachter
  textEl.innerHTML = nextWord.substring(0, currentLength   1);
    
  setTimeout(addNextWord, 240);
  
  
}  
 #first-section{
  z-index: 4;
  background-image: linear-gradient(to top, #205ba8 0%, #537895 100%);
  position: relative;
  width: 100%;
  min-height: 100vh;
  display: flex;


}

.inspire{
  padding: 0;
  margin: 0;
  position: absolute;
  top: 0;
  left: 10%;
  color: #fff;
  font-size: 50px;
  font-weight: 600;
  font-family: sans-serif;
}

.change-text {
  position: absolute;
  bottom: 0;
  left: 10%;
  color: #fff;
  line-height: 500px;
  font-size: 70px;
  font-weight: 900;
  cursor: context-menu;

}

@keyframes blinking {
  0%    { opacity: 0; }
  50%   { opacity: 0; }
  51%   { opacity: 1; }
  100%  { opacity: 1; }
}
.change-text:after {
  content: '_';
  animation: blinking 1.2s infinite;
  
}  
 <section id="first-section">
    <h1 class="inspire" data-aos="fade-right">
      HERE TO:
    </h1>
    <div class="change-text" data-aos="fade-right">Design</div>


  </section>  

Комментарии:

1. Вы должны обернуть каждое слово в элемент (например, <span> ), имеющий класс, определяющий шрифт (или встроенный атрибут стиля).

2. Я вообще не вижу никаких эффектов в Firefox и Chrome на Mac, там просто написано here to: ; ничего не происходит,. Также в ответах…

3. @ikiK развернуть страницу.

Ответ №1:

вы можете использовать массив объектов для слов. Добавьте свои пользовательские шрифты к каждому слову. А затем динамически изменять шрифт. Я изменил таймер, чтобы показывать его быстро между.

 var words = [
  {
    word: 'Design',
    font: 'Cursive'
  },
  {
    word: 'Create',
    font: 'Serif'
  },
  {
    word: 'Dream',
    font: 'Sans-Serif'
  },
  {
    word: 'Inspire',
    font: `'Pangolin', cursive`
  }
],
    currentStep = 0,
    textEl = document.querySelector('.change-text'),
    oldWord = '';


setTimeout(changeWord, 2000);

function changeWord() {
  oldWord = textEl.innerHTML;
  
  // check if there is a word atm or not
  if (oldWord.length < 1) {

    if (currentStep !== words.length -1) {
          currentStep   ;
    }else {
      currentStep = 0;
    }
    textEl.style.fontFamily = words[currentStep].font;
    addNextWord();
  } else {
    setTimeout(deleteWord, 100);
  }
  
};

function deleteWord() {
  var WordLength = oldWord.length,
      currentWord = textEl.innerHTML,
      currentLength = currentWord.length;
  

  // The word is deleted so, start adding in the new one
  if (currentLength < 1) {
    changeWord();
    return;
  }
  
  // Remove a charachter
  textEl.innerHTML = currentWord.substring(0, currentLength - 1);
  
  setTimeout(deleteWord, 140);
}

function addNextWord() {
  var currentWord = textEl.innerHTML,
      currentLength = currentWord.length,
      nextWord = words[currentStep].word,
      nextWordLength = nextWord.length;
    
  
  if (currentLength === nextWordLength) {
    changeWord();
    return;
  }
  
  
  
  // add a charachter
  textEl.innerHTML = nextWord.substring(0, currentLength   1);
    
  setTimeout(addNextWord, 240);
  
  
}  
 @import url('https://fonts.googleapis.com/css2?family=Pangolinamp;display=swap');

#first-section{
  z-index: 4;
  background-image: linear-gradient(to top, #205ba8 0%, #537895 100%);
  position: relative;
  width: 100%;
  min-height: 100vh;
  display: flex;


}

.inspire{
  padding: 0;
  margin: 0;
  position: absolute;
  top: 0;
  left: 10%;
  color: #fff;
  font-size: 50px;
  font-weight: 600;
  font-family: sans-serif;
}

.change-text {
  position: absolute;
  bottom: 0;
  left: 10%;
  color: #fff;
  line-height: 500px;
  font-size: 70px;
  font-weight: 900;
  cursor: context-menu;

}

@keyframes blinking {
  0%    { opacity: 0; }
  50%   { opacity: 0; }
  51%   { opacity: 1; }
  100%  { opacity: 1; }
}
.change-text:after {
  content: '_';
  animation: blinking 1.2s infinite;
  
}  
 <section id="first-section">
    <h1 class="inspire" data-aos="fade-right">
      HERE TO:
    </h1>
    <div class="change-text" data-aos="fade-right"></div>


  </section>  

Ответ №2:

Следуйте моему примеру, я добавляю простое if, запускаю счетчик массива word и, наконец, меняю шрифт.

 var words = ['Design','Create','Dream', 'Inspire'],
    currentStep = 0,
    textEl = document.querySelector('.change-text'),
    oldWord = '';


setTimeout(changeWord, 2000);

function changeWord() {
  oldWord = textEl.innerHTML;
  
  // check if there is a word atm or not
  if (oldWord.length < 1) {

    if (currentStep !== words.length -1) {
          currentStep   ;
    }else {
      currentStep = 0;
    }
    if(currentStep == 0){
  textEl.style.fontFamily = "Impact,Charcoal,sans-serif";
  }else  if(currentStep== 1){
   textEl.style.fontFamily = "Times New Roman";
  }else  if(currentStep == 2){
   textEl.style.fontFamily = "Palatino Linotype";
  }else  if(currentStep == 3){
   textEl.style.fontFamily = "Georgia";
  }
    addNextWord();
  } else {
    setTimeout(deleteWord, 1400);
  }
  
};

function deleteWord() {
  var WordLength = oldWord.length,
      currentWord = textEl.innerHTML,
      currentLength = currentWord.length;
  

  // The word is deleted so, start adding in the new one
  if (currentLength < 1) {
    changeWord();
    return;
  }
  
  // Remove a charachter
  textEl.innerHTML = currentWord.substring(0, currentLength - 1);
  
  setTimeout(deleteWord, 140);
}

function addNextWord() {
  
  var currentWord = textEl.innerHTML,
      currentLength = currentWord.length,
      nextWord = words[currentStep],
      nextWordLength = nextWord.length;
    
  
  if (currentLength === nextWordLength) {
    changeWord();
    return;
  }
  
  // add a charachter
  textEl.innerHTML = nextWord.substring(0, currentLength   1);
    
  setTimeout(addNextWord, 240);
  
  
}  
 #first-section{
  z-index: 4;
  background-image: linear-gradient(to top, #205ba8 0%, #537895 100%);
  position: relative;
  width: 100%;
  min-height: 100vh;
  display: flex;


}

.inspire{
  padding: 0;
  margin: 0;
  position: absolute;
  top: 0;
  left: 10%;
  color: #fff;
  font-size: 50px;
  font-weight: 600;
  font-family: sans-serif;
}

.change-text {
  position: absolute;
  bottom: 0;
  left: 10%;
  color: #fff;
  line-height: 500px;
  font-size: 70px;
  font-weight: 900;
  cursor: context-menu;

}

@keyframes blinking {
  0%    { opacity: 0; }
  50%   { opacity: 0; }
  51%   { opacity: 1; }
  100%  { opacity: 1; }
}
.change-text:after {
  content: '_';
  animation: blinking 1.2s infinite;
  
}  
 <section id="first-section">
    <h1 class="inspire" data-aos="fade-right">
      HERE TO:
    </h1>
    <div class="change-text" data-aos="fade-right">Design</div>


  </section>  

Ответ №3:

Вы можете добавить все шрифты, которые хотите использовать, в массив, затем создать функцию, которая выбирает их случайным образом.

 var fonts = ['verdana', 'arial', 'timesNewRoman'];

function changeFont() {                                                                                                                           
  var font = fonts[Math.floor(Math.random() * fonts.length)];
  textEl.style.fontFamily = font;
}
  

Затем вызовите эту функцию сразу после вызова addNextWord

 function changeWord() {
    oldWord = textEl.innerHTML;
    
    // check if there is a word atm or not
    if (oldWord.length < 1) {
  
      if (currentStep !== words.length -1) {
            currentStep   ;
      }else {
        currentStep = 0;
      }
      addNextWord();
      changeFont();  // Call changeFont Here!!                                                                                                                                
    } else {
      setTimeout(deleteWord, 1400);
    }
    
  }