Изменить изображение с типом написания текстового эффекта с помощью jQuery - PullRequest
0 голосов
/ 19 сентября 2019

Я хотел бы изменить изображение после каждой напечатанной строки.В примере показаны только 2 строки и 2 изображения, но будет много строк и изображений.

Изображение должно измениться после изменения содержимого строки.

Как мне это сделать?

JSDiffle: https://jsfiddle.net/13ujowkL/

HTML

  <div class="output" id="output">
    <h1 class="cursor"></h1>
  </div>
  <div class="images">
    <img src="https://i.postimg.cc/4Y054xz3/video-1.jpg">
    <img src="https://i.postimg.cc/8jt43HcM/video-2.jpg">
  </div>

CSS

.cursor::after {
  content: ' ';
  display: inline-block;
  margin-left: 3px;
  background-color: #00b69d;
  animation-name: blink;
  animation-duration: 0.5s;
  animation-iteration-count: infinite;
}
h1.cursor::after {
  height: 24px;
  width: 13px;
}
p.cursor::after {
  height: 13px;
  width: 6px;
}
@keyframes blink {
  0% { opacity: 1; }
  49% { opacity: 1; }
  50% { opacity: 0; }
  100% { opacity: 0; }
}

jQuery

// values to keep track of the number of letters typed, which quote to use. etc. Don't change these values.
var i = 0,
    a = 0,
    isBackspacing = false,
    isParagraph = false;

// Typerwrite text content. Use a pipe to indicate the start of the second line "|".  
var textArray = [
  "This line would show video-1.jpg", 
  "And this would show video-2.jpg"
];

// Speed (in milliseconds) of typing.
var speedForward = 100, //Typing Speed
    speedWait = 1000, // Wait between typing and backspacing
    speedBetweenLines = 1000, //Wait between first and second lines
    speedBackspace = 25; //Backspace Speed

//Run the loop
typeWriter("output", textArray);

function typeWriter(id, ar) {
  var element = $("#" + id),
      aString = ar[a],
      eHeader = element.children("h1"), //Header element
      eParagraph = element.children("p"); //Subheader element

  // Determine if animation should be typing or backspacing
  if (!isBackspacing) {

    // If full string hasn't yet been typed out, continue typing
    if (i < aString.length) {

      // If character about to be typed is a pipe, switch to second line and continue.
      if (aString.charAt(i) == "|") {
        isParagraph = true;
        eHeader.removeClass("cursor");
        eParagraph.addClass("cursor");
        i++;
        setTimeout(function(){ typeWriter(id, ar); }, speedBetweenLines);

      // If character isn't a pipe, continue typing.
      } else {
        // Type header or subheader depending on whether pipe has been detected
        if (!isParagraph) {
          eHeader.text(eHeader.text() + aString.charAt(i));
        } else {
          eParagraph.text(eParagraph.text() + aString.charAt(i));
        }
        i++;
        setTimeout(function(){ typeWriter(id, ar); }, speedForward);
      }

    // If full string has been typed, switch to backspace mode.
    } else if (i == aString.length) {

      isBackspacing = true;
      setTimeout(function(){ typeWriter(id, ar); }, speedWait);

    }

  // If backspacing is enabled
  } else {

    // If either the header or the paragraph still has text, continue backspacing
    if (eHeader.text().length > 0 || eParagraph.text().length > 0) {

      // If paragraph still has text, continue erasing, otherwise switch to the header.
      if (eParagraph.text().length > 0) {
        eParagraph.text(eParagraph.text().substring(0, eParagraph.text().length - 1));
      } else if (eHeader.text().length > 0) {
        eParagraph.removeClass("cursor");
        eHeader.addClass("cursor");
        eHeader.text(eHeader.text().substring(0, eHeader.text().length - 1));
      }
      setTimeout(function(){ typeWriter(id, ar); }, speedBackspace);

    // If neither head or paragraph still has text, switch to next quote in array and start typing.
    } else { 

      isBackspacing = false;
      i = 0;
      isParagraph = false;
      a = (a + 1) % ar.length; //Moves to next position in array, always looping back to 0
      setTimeout(function(){ typeWriter(id, ar); }, 50);

    }
  }
}

1 Ответ

1 голос
/ 19 сентября 2019

Вы можете использовать images объект,

var images = {
  0: { 
  "urls": [
     "https://i.ytimg.com/vi/d_T5P-zIIAs/maxresdefault.jpg",
     "https://i.ytimg.com/vi/kpvKA0vhaT0/maxresdefault.jpg"
  ]},
  1: {
  "urls": [
     "https://i.ytimg.com/vi/kpvKA0vhaT0/maxresdefault.jpg",
     "https://i.ytimg.com/vi/d_T5P-zIIAs/maxresdefault.jpg"
  ]},
  2: { 
    "urls": [
     "https://i.ytimg.com/vi/d_T5P-zIIAs/maxresdefault.jpg",
     "https://i.ytimg.com/vi/kpvKA0vhaT0/maxresdefault.jpg"
  ]}
}

Затем изменить изображения с помощью функции,

function changeImage(number) {
  var imagesArr = [];
  images[number].urls.forEach(function(url){
    imagesArr.push('<img src="'+ url +'">');
  });

  $('.images').html(imagesArr);
}

Вам необходимо вызвать эту функцию в последнем else блоке,

// If neither head or paragraph still has text, switch to next quote in array and start typing.
} else {
   changeImage(a);
}

Рабочий образец: https://jsbin.com/valayohota/1/edit?html,js,console,output

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...