gpt4 book ai didi

javascript - 使用脚本或 CSS 动画替换/旋转句子中的多个单词

转载 作者:行者123 更新时间:2023-12-04 09:15:14 25 4
gpt4 key购买 nike

我试图在我的网站(Wordpress)上的一个段落中替换/旋转几个不同的单词。我找到了一个脚本,它允许我更改一组单词,但无法弄清楚如何更改下一组单词。

var words = ["one", "two", "three"];
var i = 0;
var text = "one";

function _getChangedText() {
i = (i + 1) % words.length;
console.log(words[i]);
console.log(i);
return text.replace(/one/, words[i]);
}

function _changeText() {
var txt = _getChangedText();
console.log(txt);
document.getElementById("changer").innerHTML = txt;
}
setInterval("_changeText()", 3000);
<h4>Count to <span id="changer">one</span> and (four, five, six) and (seven, eight, nine).</h4>

最佳答案

这可能就是你想要的。如果您了解它的工作原理,则可以轻松扩展此代码。我添加了评论,以便您可以理解。
如果这对您有帮助,请考虑将其批准为答案。

; // This is a javascript object used as a hashmap
var changeList = {
"one": "two",
"two": "three",
"three": "four",
"four": "five",
"five": "six",
"six": "seven",
"seven": "eight",
"eight": "nine",
// ...
}

function _changeText() {
let els = document.querySelectorAll('.word-changer');
//iterate over all .word-changer elements
for (let i = 0; i < els.length; i++) {
let el = els[i];
// read out elements data-counter and data-max attributes
let counter = parseInt(el.dataset.counter);
let max = parseInt(el.dataset.max);

if(counter < max ) {
// Update counter and replace word based on the "hashmap"
counter++;
el.innerHTML = changeList[el.textContent]; // This is where the words get swapped
el.dataset.counter = counter;
}
}
}

setInterval(_changeText, 3000);
<h4>
Count to <span class="word-changer" data-counter="0" data-max="2">one</span> and <span class="word-changer" data-counter="0" data-max="2">four</span> and <span class="word-changer" data-counter="0" data-max="2">six</span>.
</h4>

关于javascript - 使用脚本或 CSS 动画替换/旋转句子中的多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63255370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com