Javascript打字效果

时间:2013-11-11 17:32:46

标签: javascript

问题来自与last time相同的问题。我的网站运行静态域名,因此我希望能够在每个站点上使用此脚本,而无需复制副本。

它用作打字文本效果,我希望能够定义从网页本身而不是脚本打印出来的文本。

的Javascript

var index = 0;
var text = 'Text';

function type()
{
    document.getElementById('screen').innerHTML += text.charAt(index);
    index += 1;
    var t = setTimeout('type()',100);
}

我已经尝试摆弄代码并使用与我之前的帖子相同的方法,但我似乎无法让它工作。

6 个答案:

答案 0 :(得分:4)

好的,我不喜欢上面的任何代码。一旦到达输入文本的末尾,您的原始代码也不会停止运行,我也不相信任何其他建议的解决方案也会停止。

这是纯JS中的重写函数:

function type(i, t, ie, oe) {
    input = document.getElementById(ie).innerHTML;
    document.getElementById(oe).innerHTML += input.charAt(i);
    setTimeout(function(){
        ((i < input.length - 1) ? type(i+1, t, ie, oe) : false);
    }, t);
}

您可以这样打电话:

type(0, 100, "text", "screen");

参数包括:beginning indexspeedinput elementoutput element

您的HTML看起来像这样:

<div id="screen"></div>
<div id="text" style="display:none">Hello Bobby</div>

只要您相应地更新参数,就可以将div重命名为您喜欢的任何内容。我确信有一种更简单的方式来写这个,但我最喜欢这种方法。

<小时/> 的演示

function type(i, t, ie, oe) {
    input = document.getElementById(ie).innerHTML;
    document.getElementById(oe).innerHTML += input.charAt(i);
    setTimeout(function(){
        ((i < input.length - 1) ? type(i+1, t, ie, oe) : false);
    }, t);
}

type(0, 100, "text", "screen");
<div id="screen"></div>
<div id="text" style="display:none">Hello Bobby</div>

答案 1 :(得分:3)

不错的问题,LMGTFY过去常常让我傻笑。我想你可能会发现以下内容非常容易随处扔掉。它只是添加到目标容器的一些属性,以及启动打字机的调用。

在这里,我同时运行其中4个只是为了踢。在这个例子中,使用少数注释行可能值得使用theEachNode。如果getElementsByClassName的结果是一个真正的数组,你可以只调用数组所具有的.forEach方法。不幸的是,nodeList类似但不相同 - 因此需要这样的功能。我在使用它之前就已经意识到它没有它可能更清楚。无论如何,这是我多次找到的功能。我会把它留在那里作为对这个有趣的问题的考虑。

function forEachNode(nodeList, func) {
  var i, n = nodeList.length;
  for (i = 0; i < n; i++) {
    func(nodeList[i], i, nodeList);
  }
}

window.addEventListener('load', mInit, false);

function typeWriter(el) {
  var myDelay = el.getAttribute('keyDelay');

  if (el.getAttribute('curIndex') == undefined)
    el.setAttribute('curIndex', 0);

  var curIndex = el.getAttribute('curIndex');
  var curStr = el.getAttribute('typewriterdata');
  el.innerHTML += curStr.charAt(curIndex);
  curIndex++;
  el.setAttribute('curIndex', curIndex);

  if (curIndex < curStr.length)
    setTimeout(callback, myDelay);
  else {
    if (el.getAttribute('nextline') != undefined) {
      var nextTgt = el.getAttribute('nextline');
      typeWriter(document.getElementById(nextTgt));
    }
  }

  function callback() {
    typeWriter(el);
  }
}

function mInit() {
  typeWriter(document.getElementById('line1'));

  var i, n, elementList;
  elementList = document.getElementsByClassName('autoType');
  forEachNode(elementList, typeWriter);
  //	n = elementList.length;
  //	for (i=0; i<n; i++)
  //		typeWriter( elementList[i] );
}
.multi {
  border: solid 2px #333333;
  width: 400px;
}
<body>
  <div class='autoType' typewriterdata='Enter this string letter by letter' keydelay='300'></div>
  <div class='autoType' typewriterdata='Enter this string letter by letter' keydelay='200'></div>
  <div class='autoType' typewriterdata='This is short but slooooow' keydelay='1000'></div>
  <div class='autoType' typewriterdata='The rain falls mainly on the plain in Spain' keydelay='100'></div>

  <div class='multi'>
    <div id='line1' typewriterdata='This is line 1' keydelay='300' nextline='line2'></div>
    <div id='line2' typewriterdata='This is line 2' keydelay='300' nextline='line3'></div>
    <div id='line3' typewriterdata='This is line 3' keydelay='300' nextline='line4'></div>
    <div id='line4' typewriterdata='This is line 4' keydelay='300'></div>
  </div>
</body>

答案 2 :(得分:1)

您可以将网页中的文字嵌入隐藏的元素中,如下所示:

<强> HTML

<span id="hiddenText" style="display: none">Text you want to type out.</span>

然后您就可以从网页本身获取文字:

<强>的Javascript

var text = document.getElementById('hiddenText').innerHTML;

以下是您可以看到的jsfiddle:http://jsfiddle.net/FMq6d/。 这会对您的代码进行最少的更改。

答案 3 :(得分:1)

如果你想定义它打印出来的文本,你应该通过参数传递文本,如果我正确理解你的问题。

试着搞砸这个:

var type = function( elem , text , index )
{
    var index = index||0;
    elem.innerHTML += text.charAt(index);
    index++;

    var t = setTimeout(function(){
        type( elem , text , index );
    },100);
}
type( document.getElementById('screen') , 'How\'re You?' );
<p id="screen">Hello, </p>

答案 4 :(得分:1)

2年后:

看看这个很棒的Typing & erasing effect plus a blinking cursor - CodePen

坚果壳

var index = 0;
var text = "The Typing Effect - In a Nutshell";

function type(){
  var screenEl = $('#screen');
  screenEl.html(text.substr(0, index++));

  if (index < text.length) {
    // Feel free to type
    setTimeout('type()', 50);
  } else {
    // Reset and restart.
    index = 0;
    text = '';
  }
};

type();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="screen"></p>

答案 5 :(得分:1)

这是一种使用承诺在按键之间休眠的方法。

这是Github上的回购的link,但代码基本上是这样的:

class Typer {

    constructor(typingSpeed, content, output) {

        this.typingSpeed = typingSpeed;
        // Parses a NodeList to a series of chained promises
        this.parseHtml(Array.from(content), output);
    };

    makePromise(node, output) {

        if (node.nodeType == 1) // element 
        {
            // When a new html tag is detected, append it to the document
            return new Promise((resolve) => {
                var tag = $(node.outerHTML.replace(node.innerHTML, ""));
                tag.appendTo(output);
                resolve(tag);
            });

        } else if (node.nodeType == 3) // text
        {
            // When text is detected, create a promise that appends a character
            // and sleeps for a while before adding the next one, and so on...
            return this.type(node, output, 0);
        } else {
            console.warn("Unknown node type");
        }
    }

    parseHtml(nodes, output) {
        return nodes.reduce((previous, current) => previous
            .then(() => this.makePromise(current, output)
                .then((output) => this.parseHtml(Array.from(current.childNodes), output))), Promise.resolve());
    }

    type(node, output, textPosition) {
        var textIncrement = textPosition + 1;

        var substring = node.data.substring(textPosition, textIncrement);

        if (substring !== "") {
            return new Promise(resolve => setTimeout(resolve, this.typingSpeed))
                .then(() => output.append(substring))
                .then(() => this.type(node, output, textIncrement));
        }

        return Promise.resolve(output);
    }
}