使用数组数据链接属性

car*_*ium 5 javascript

不确定我的问题的标题措词是否正确,如果错误,请更正我。

我正在使用TypeIt来显示对话框。立即使用其上下文示例:

new TypeIt('#myElement', {
  // options
})
.type("This is a sentence.")
.pause(500)
.type(" A second sentence after waiting 500 milliseconds")
.go();
Run Code Online (Sandbox Code Playgroud)

Codepen上的示例预览:https ://codepen.io/carpenumidium/pen/yLBawrZ

我试图显示一个数组中的随机对话,但是我的方法导致从第一个对话开始同时从列表中一次显示每个对话。

我的密码(单击蓝色栏上的对话框出现)

Javascript:

var dialogue = new TypeIt('#dialogues', {
    speed: 50,
    waitUntilVisible: true,
    cursor: false
});

var dialogueText = [
    dialogue.type("First line of a dialogue. ").pause(500).break().type("Second line of dialogue."),
    dialogue.type("First line of second dialogue. ").pause(500).break().type("Second line of dialogue."),
    dialogue.type("First line of third dialogue. ").pause(500).break().type("Second line of dialogue."),
    dialogue.type("First line of fourth dialogue. ").pause(500).break().type("Second line of dialogue.")
    ];

var refreshDialogueBox = document.querySelector(".dialogue-box");
var dialoguesLength = dialogueText.length - 1;

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

var randomDialogue = getRandomInt(dialoguesLength);

refreshDialogueBox.addEventListener("click", function() {
    dialogue.reset();
    dialogueText[3].go();
});
Run Code Online (Sandbox Code Playgroud)

感谢你的帮助!谢谢!

jun*_*var 2

问题本质上是您创建一个实例 TypeIt,将所有 4 对文本附加到该实例,并将该实例在数组中存储 4 次dialogueText

TypeIt.type()不返回新实例,而是修改原始实例。

解决方案是简单地创建 4 个实例TypeIt,例如

let x = () =>
    new TypeIt('#dialogues', {
        speed: 50,
        waitUntilVisible: true,
        cursor: false
    });

var dialogueText = [
    x().type("1.1 First line of a dialogue. ").pause(500).break().type("1.2 Second line of dialogue."),
    x().type("2.1 First line of second dialogue. ").pause(500).break().type("2.2 Second line of dialogue."),
    x().type("3.1 First line of third dialogue. ").pause(500).break().type("3.2 Second line of dialogue."),
    x().type("4.1 First line of fourth dialogue. ").pause(500).break().type("4.2 Second line of dialogue.")
];

var refreshDialogueBox = document.querySelector(".dialogue-box");
var dialoguesLength = dialogueText.length - 1;

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

refreshDialogueBox.addEventListener("click", function() {
    let dialog = dialogueText[getRandomInt(dialoguesLength)];
    dialog.reset();
    dialog.go();
});
Run Code Online (Sandbox Code Playgroud)

https://codepen.io/junvar00/pen/QWLKRyj

PS 感谢您提供一个正在运行的最小代码示例,它对回答问题有很大帮助!