javascript - 在wixsite的javascript中循环遍历数组
问题描述
我试图获得进入我的wixsite的单词“旋转门”的效果,只是被下一个单词取代。
我在想这样做的方法是在 javascript 中创建一个包含我想要输入的单词的数组,然后循环遍历该数组,使用我选择的文本动画将每个单词显示在屏幕上。
我有一个需要一个单词的代码,并将其“打字”到我的 wix 网站上,但是我如何调整它以对许多单词执行相同的操作,一个接一个地退出屏幕(几乎就像正在键入单词的幻灯片? )
这是我的代码:
> import wixData from 'wix-data';
>
> let interval; let timeInterval = 350; let typeStr = "Invest"; let
> typeIdx; let htmlStr = ''; let displayStr;
>
> $w.onReady(function () {
// Get the original html string, and split it into two pieces.
// In the process, remove the separator !##!
// By saving the original html, we preserve the style of the text to display.
if (htmlStr.length === 0) { // just get the original html text the first time
htmlStr = $w("#typewriterPage").html;
}
$w("#typewriterPage").html = ''; // don't show the original text
let strPieces = htmlStr.split("!##!");
displayStr = ''; // init string that we will "type" to
typeIdx = 0; // start at beginning of string we want to "type"
// Declare an interval function that will run in the background.
// This function will be triggered by the defined timeInterval.
interval = setInterval(function () {
// Get next char from string to be typed and concatenate to the display string.
displayStr = displayStr + typeStr[typeIdx++];
// Make a sandwich with the display string in between the original html pieces.
$w("#typewriterPage").html = strPieces[0] + displayStr + strPieces[1];
// Stop the interval from running when we get to the last character to by "typed".
if (typeIdx === typeStr.length) clearInterval(interval);
}, timeInterval);
});
解决方案
const $w = document.querySelector.bind(document);
Object.defineProperty($w('#typewriterPage'), 'html', {
get: function () { return this.innerHTML },
set: function (html) { this.innerHTML = html }
});
// ignore everything above this comment
const typewriterPage = $w('#typewriterPage');
const carouselWords = ['Invest', 'Finance', 'Borrow', 'Lend'];
typeWords(carouselWords, typewriterPage.html.split('!##!'));
async function typeWords(words, style) {
while (true) {
words.unshift(words.pop());
const [word] = words;
await typeWord(word, style);
}
}
function typeWord(word, style) {
const chars = [...word];
let stack = '';
return new Promise(resolve => {
const interval = setInterval(() => {
if (!chars.length) {
resolve();
clearInterval(interval);
return;
}
stack += chars.shift();
typewriterPage.html = style[0] + stack + style[1];
}, 250);
});
}
<span id='typewriterPage'><u>!##!</u></span>
推荐阅读
- jquery - 如何使用复选框制作一个赞按钮以将随机生成的引号存储到数组中
- javascript - 使用材质 ui 在开关内添加文本
- aws-glue - 使用 aws glue python shell 连接到 Oracle RDS 数据库
- php - 每个页面和页面的每个输入字段的基于动态角色的访问控制
- python-2.7 - 创建永久(固定)conda 环境
- r - 在数据框中的多列中仅保留负值
- javascript - 为什么 for (...in...) 循环在遍历对象方法时不返回键
- javascript - 向 Netlify 提供服务命令
- python - 如何读取 OneDrive 的所有文件并用 Python 进行复制
- javascript - 使用 express 将 PDF 上传到 mongoDB