简体   繁体   English

在 Javascript 中创建一个可重用的类型编写器效果函数?

[英]Create a re-usable type writer effect function in Javascript?

I know the basics of what I need to do here, but my attempt at coding it is riddled with problems so here is what I want to do.我知道我需要在这里做什么的基础知识,但是我对它进行编码的尝试充满了问题,所以这就是我想要做的。

Define a series of strings to be called up into a function that types it onto the screen with a slight delay between each letter.定义一系列要调用到函数中的字符串,该函数将其键入到屏幕上,每个字母之间有轻微的延迟。 I've found some examples of people making typewriter title cards, but these are not designed to be used like functions that can be called up on the fly.我发现了一些人们制作打字机标题卡的例子,但它们的用途并不是像可以即时调用的功能那样使用。 For this particular project, we need the text to function like a makeshift dialog system that won't be called up until the function is called with a specific string.对于这个特定的项目,我们需要文本像临时对话系统一样发挥作用,在使用特定字符串调用函数之前不会调用该系统。 Like a button with " onclick="dialogFunction(idOfStringToBeTyped) " what I have looks like this:就像一个带有" onclick="dialogFunction(idOfStringToBeTyped) "的按钮,我看起来像这样:

var d1Example = "Hello, I am example dialog";

function dialog(dialogString) {
    var i;
for (i = 0; i <= dialogString.length(); i++) { 
    document.write( dialogString.charAt(i) );
     java.lang.Thread.sleep(50);
}}

So my attempts to code the content has been... brute force-y...所以我对内容进行编码的尝试是……蛮力的……

EDIT: to include my attempt, should have been there in the first place, sorry about that.编辑:包括我的尝试,应该首先在那里,抱歉。

This, in theory, should work, but in practice does nothing.这在理论上应该有效,但实际上没有任何作用。 I probably have a syntax error.我可能有语法错误。 but really it doesn't make sense to me why this doesn't work.但对于我来说为什么这不起作用真的没有意义。

You should look into the JavaScript functions setTimeout and Math.random() .您应该查看 JavaScript 函数setTimeoutMath.random()

You can use Math.random() to create a floating point integer between 0 and 1.您可以使用Math.random()创建一个介于 0 和 1 之间的浮点整数。

var multipule = 5
var rand = Math.random();  // 0.5680401974599227
var randInSeconds = rand * multipule // 2.840200987299614
var waitInSeconds = Math.round(randInSeconds) // 3

Then use the the setTimeout out method to call the code that writes each character.然后使用setTimeout out 方法调用写入每个字符的代码。 setTimeout takes two parameters, a function and the number of seconds: setTimeout需要两个参数,一个函数和秒数:

var writeCharacter = function(){
  ... 
};

setTimeout(writeCharacter, 300);

I'll leave it to you to work out all the timing.我会把它留给你来计算所有的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM