如何根据javascript中图片的标题显示图片?

How can I display images based on the title of the image in javascript?

我有一个文件夹,每个字母都有图片。给定一个句子,我希望能够遍历句子中的所有字母,并一次显示每个字母相关的图像 3 秒。例如,对于句子“葡萄”,标题为“g”的图片会显示 3 秒,然后继续显示下一个字母,等等。现在,我按照图像在文件夹中的放置顺序显示它们。我对如何实现我正在寻找的更改感到困惑,因为我是 javascript 的初学者。提前谢谢你,这是我现在拥有的:

            var index = 0;
            change();
            var phrase = "my sentence";
    
            function change() {
                 var pics = document.getElementsByClassName('pictures');
    
                 for(var i = 0; i < pics.length; i++) { 
                     pics[i].style.display = "none"; 
                 }
    
                 for (var j = 0; j < phrase.length; j++) {
                     for (var k = 0; k < pictures.length; k++) {
                         var image = pictures[k].getElementsByTagName("img")[0];
                         var title = image.getAttribute("title");
                         if (phrase[j] == title) {
                             pictures[k].style.display = "block";
                         }
                     }
                 }
    
                 setTimeout(change, 3000);
             }
    <section>
        <img class="slides" src="letter_images/a.jpg" style="width:50%">
        <img class="slides" src="letter_images/b.jpg" style="width:50%">
        <img class="slides" src="letter_images/c.jpg" style="width:50%">
        <img class="slides" src="letter_images/d.jpg" style="width:50%">
        <img class="slides" src="letter_images/e.jpg" style="width:50%">
        <img class="slides" src="letter_images/f.jpg" style="width:50%">
        <img class="slides" src="letter_images/g.jpg" style="width:50%">
        <img class="slides" src="letter_images/h.jpg" style="width:50%">
        <img class="slides" src="letter_images/i.jpg" style="width:50%">
        <img class="slides" src="letter_images/j.jpg" style="width:50%">
        <img class="slides" src="letter_images/k.jpg" style="width:50%">
        <img class="slides" src="letter_images/l.jpg" style="width:50%">
        <img class="slides" src="letter_images/m.jpg" style="width:50%">
        <img class="slides" src="letter_images/n.jpg" style="width:50%">
        <img class="slides" src="letter_images/o.jpg" style="width:50%">
        <img class="slides" src="letter_images/p.jpg" style="width:50%">
        <img class="slides" src="letter_images/q.jpg" style="width:50%">
        <img class="slides" src="letter_images/r.jpg" style="width:50%">
        <img class="slides" src="letter_images/s.jpg" style="width:50%">
        <img class="slides" src="letter_images/t.jpg" style="width:50%">
        <img class="slides" src="letter_images/u.jpg" style="width:50%">
        <img class="slides" src="letter_images/v.jpg" style="width:50%">
        <img class="slides" src="letter_images/w.jpg" style="width:50%">
        <img class="slides" src="letter_images/x.jpg" style="width:50%">
        <img class="slides" src="letter_images/y.jpg" style="width:50%">
        <img class="slides" src="letter_images/z.jpg" style="width:50%">
    </section>

您需要遍历 phrase 变量中的字母,逐一查找每个字母。从那里,您需要找出它在字母表中的位置(下面的 letters 字符串)。这应该给你一个从 0 到 25 的数字。这应该与你的 slides 集合中的索引号相匹配,这样你就可以显示具有匹配索引号的那个。

    var index = 0;
    var phrase = "my sentence";
    var letters = "abcdefghijklmnopqrstuvwxyz";
    var tt;

    function change() {
         var pics = document.getElementsByClassName('slides');

         for(var i = 0; i < pics.length; i++) { 
             pics[i].style.display = "none"; 
         }

         let thisLetter = phrase.substr(index, 1);
         if (thisLetter != " ") {
           let thisPos = letters.indexOf(thisLetter);
           pics[thisPos].style.display = "block";
         } else {
           pics[pics.length - 1].style.display = "block";
         }
        index++;
        if (index != phrase.length) {
          tt = setTimeout(change, 3000);
        } else {
          for(var i = 0; i < pics.length; i++) { 
             pics[i].style.display = "none"; 
          }
        }
     }

如果所有图像都可用,则无法进行测试。该代码确实 运行,但您需要在本地进行检查以确保万无一失。

我建议遍历句子的每个字母。每个字母将在 index * 3000ms 时显示(其中 index 是句子中字母的索引 - 第一个字母索引 = 0,第二个字母索引 = 1,...)

这是一个代码示例

const imgLetter = document.getElementById('letter');
const sentence = 'hello world';

sentence
  .split('')
  .filter(letter => /[a-z ]/i.test(letter)) // consider only letters and space
  .forEach((letter, index) => {
    setTimeout(_ => {
      letter = letter !== ' ' ? letter : 'Rest'; 
      imgLetter.src = `letter_images/${letter}.jpg`;
      imgLetter.alt = letter;
    }, index * 3000);
  });
  
<section>
    <img class="slides" src="" style="width:50%" id="letter">
</section>

这是另一种方法。加载您需要的所有图像,然后循环遍历它们。这样您就不必加载额外的图像。如果你的词组很长并且有重复的字母并且包含最多的字母,ATD 的方法可能会更好。

let phrase = 'grape',
    index = 0;
    output = document.querySelector('#output');

//Frist we create the phrase with images, all hidden

for (let i = 0; i < phrase.length; i++) {
  output.innerHTML += `<img class="slides" src="letter_images/${phrase[i]}.jpg" style="width:50%" alt="${phrase[i]}">`
}

//Now we show each one, one at a time

var loop = window.setInterval(showNextLetter, 3000 /*3 sec*/);

showNextLetter();

function showNextLetter() {
  let nextLetter = output.children[index],
      oldLetter = document.querySelector('.slides.shown');

  //Make sure it exists
  if (oldLetter) oldLetter.classList.remove('shown');

  nextLetter.classList.add('shown');

  index++;
  
  if (index >= phrase.length) index = 0;
}
.slides {
  display: none;
}

.slides.shown {
  display: block;
}
<div id="output"></div>

正如 ATD 所指出的,setTimeout 不保证该操作将在请求的时间间隔内执行 ,因此我尝试查看对于没有 setTimeout.

的解决方案

我的想法是在 javascript 中用循环创建完整的句子,然后使用 CSS 动画一次显示一张图像

const sentence = document.getElementById('sentence');
const mySentence = 'hello world';

const letters = mySentence.split('').filter(letter => /[a-z ]/i.test(letter));

sentence.style.setProperty('--letter-count', letters.length);

letters.forEach(letter => {
  const imgLetter = document.createElement('img');
  letter = letter !== ' ' ? letter : 'Rest';
  imgLetter.src = `letter_images/${letter}.jpg`;
  imgLetter.alt = letter;
  sentence.append(imgLetter);
});
#sentence {
  display: flex;
  overflow: hidden;
}

/* images must have #sentence same size */
#sentence,
#sentence > img {
  width: 200px;
  height: 200px;
}

#sentence > img:first-child {
  animation-name: slide;
  animation-duration: calc(3s * var(--letter-count));
  animation-timing-function: steps(var(--letter-count), end);
  animation-fill-mode: forwards;
}

/* -200px = minus the width of #sentence */
@keyframes slide {
  from {margin-left: 0}
  to {margin-left: calc(-200px * var(--letter-count))}
}
<section id="sentence"></section>