我正在编辑一个代码,该代码将在一段时间后更改文本,以替换新文本并替换之前的文本。一切似乎都正常,但我的浏览器控制台显示单词未定义:
TypeError:单词[currentWordIndex]未定义
即使我使用过:
var words = document.querySelectorAll(“。word”);
我希望不会出现“ .word”类。
这是我关于此问题的代码:
<div class="represent-body">
<div class="rotating-text">
<p>This company is</p>
<p>
<span class="word alizarin">awesome.</span>
<span class="word wisteria">beautiful.</span>
<span class="word peter-river">creative.</span>
<span class="word emerald">fabulous.</span>
<span class="word sun-flower">interesting.</span>
</p>
</div>
</div>
.represent-body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #222;
}
.rotating-text {
font-family: proxima_novabold, serif;
font-weight: 600;
font-size: 36px;
color: white;
transform: translateX(-80px);
p {
display: inline-flex;
margin: 0;
vertical-align: top;
.word {
position: absolute;
display: flex;
opacity: 0;
.letter {
transform-origin: center center 25px;
&.out {
transform: rotateX(90deg);
transition: 0.32s cubic-bezier(0.6, 0, 0.7, 0.2);
}
&.in {
transition: 0.38s ease;
}
&.behind {
transform: rotateX(-90deg);
}
}
}
}
}
// palette: https://flatuicolors.com/palette/defo
.alizarin {
color: #e74c3c;
}
.wisteria {
color: #8e44ad;
}
.peter-river {
color: #3498db;
}
.emerald {
color: #2ecc71;
}
.sun-flower {
color: #f1c40f;
}
var words = document.querySelectorAll(".word");
words.forEach(function (word) {
var letters = word.textContent.split("");
word.textContent = "";
letters.forEach(function (letter) {
var span = document.createElement("span");
span.textContent = letter;
span.className = "letter";
word.append(span);
});
});
var currentWordIndex = 0;
var maxWordIndex = words.length - 1;
words[currentWordIndex].style.opacity = "1";
var rotateText = function () {
var currentWord = words[currentWordIndex];
var nextWord = currentWordIndex === maxWordIndex ? words[0] : words[currentWordIndex + 1];
// rotate out letters of current word
Array.from(currentWord.children).forEach(function (letter, i) {
setTimeout(function () {
letter.className = "letter out";
}, i * 80);
});
// reveal and rotate in letters of next word
nextWord.style.opacity = "1";
Array.from(nextWord.children).forEach(function (letter, i) {
letter.className = "letter behind";
setTimeout(function () {
letter.className = "letter in";
}, 340 + i * 80);
});
currentWordIndex =
currentWordIndex === maxWordIndex ? 0 : currentWordIndex + 1;
};
rotateText();
setInterval(rotateText, 4000);
为什么选择“ .word”类时未定义“ words”?