gpt4 book ai didi

javascript - 如何在 JavaScript 中编写动画字符串序列(具有淡入淡出效果)?

转载 作者:行者123 更新时间:2023-11-30 09:24:08 25 4
gpt4 key购买 nike

我有以下代码循环遍历数组并定期替换 id 为“sequence”的 div 的内容。

<script>
var example = ['A','B','C','D'];

textSequence(0);
function textSequence(i) {

if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = "We Do " + example[i];
textSequence(++i);

}, 3000); // 1 second (in milliseconds)

} else if (example.length == i) { // Loop
textSequence(0);
}

}
</script>

分区:

<div id="sequence" style="font-family: Roboto; font-size: 48px;">...</div>

可运行的演示:

var example = ['A','B','C','D'];

textSequence(0);
function textSequence(i) {

if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = "We Do " + example[i];
textSequence(++i);

}, 3000); // 1 second (in milliseconds)

} else if (example.length == i) { // Loop
textSequence(0);
}

}
<div id="sequence" style="font-family: Roboto; font-size: 48px;">...</div>

在这个阶段,我想淡出每个字符串,然后淡入数组中的每个新字符串。是否可以使用 CSS 通过在每个序列的结尾和开头将 div 淡化为 0 和 1 来完成此操作?

最佳答案

您可以使用 css 动画来做到这一点,其中动画时间是数组元素变化间隔的一半。然后您还要添加 infinitealternate 属性。

const example = ['A', 'B', 'C', 'D'];
const div = document.getElementById('sequence');
let i = 0;

setInterval(function() {
div.innerHTML = "We Do " + `<span>${example[i++ % example.length]}</span>`
}, 3000)
#sequence span {
animation: change_opacity 1.5s infinite alternate;
}

@keyframes change_opacity {
0% {opacity: 0}
100% {opacity: 1}
}
<div id="sequence" style="font-family: Roboto; font-size: 48px;">...</div>

关于javascript - 如何在 JavaScript 中编写动画字符串序列(具有淡入淡出效果)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897405/

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