重复JS功能

时间:2013-09-28 20:43:21

标签: javascript jquery

我正试图让这个功能在它的循环结束时重复。我尝试将函数分配给变量并在回调中调用变量,但是失败了。我尝试在setInterval函数中包装此函数,仍然无法使其工作。

如何使此函数运行无限循环并重复自身?

$("span.text-change").typed({
     strings: ["First sentence.", "Second sentence."],
     typeSpeed: 30, // typing speed
     backDelay: 500, // pause before backspacing
     callback: function () {
         // do stuff
     }
 });

这是插件: Typed JS

jsFiddle here

6 个答案:

答案 0 :(得分:5)

这里是Typed.js的作者。我认为很棒的人很喜欢我的代码,足以挖掘它并使更多的功能工作。我绝对打算将循环设置为你可以设置的默认函数,但是现在这里有一个修复。

http://jsfiddle.net/LSsZr/8/

主要变更

self.stopArray = self.strings.length;
// instead of self.stopArray = self.strings.length-1;

这使得stopArray变量允许它在键入最后一个字符串后继续退格。否则,一旦打印完最后一个,它就会停止。


// if (self.arrayPos == self.stopArray && curStrPos == curString.length){
// animation that occurs on the last typed string
// place any finishing code here
//  self.options.callback();
//    clearTimeout();
// }

以上内容已被删除。它检查了最后输入的字符串,并在满足条件时触发了一个函数。对于循环,我们不希望这样。


else{
   self.arrayPos = 0;
   self.typewrite(self.string, self.strPos);
}

上面的if语句已添加到以下if语句中......

if (self.arrayPos < self.strings.length){

因此,如果数组位置小于数组中的字符串数量,请键入它们。否则,将位置重置为0,然后再次运行原始功能。

继续使用jsfiddle中的代码作为你的typed.js文件,然后在你想要的页面上正常运行它。虽然不再有回调()!

让我知道你的想法/问题!

修改 看起来有人在这里为插件添加了一个循环,但它只是一遍又一遍地循环最后一句:p

您必须重置发送到typewrite函数的数组中的字符串。这种情况在其他解决方案中没有发生。

答案 1 :(得分:2)

将代码放在一个间隔中是个好主意。但是,您必须在再次调用之前检查代码执行是否已完成。您可以使用用作标志的布尔变量来执行此操作。

var timerId = setInterval(function() {
    flag=true;
 if( flag){
     flag=false;
    $("div").typed({
     strings: ["First sentence.", "Second sentence."],
     typeSpeed: 30, // typing speed
     backDelay: 500, // pause before backspacing
     callback: function () {
         flag=true;
         //destroy typed plugin here. See in the api if 
         //there is a method for doing that.

     }
 });

 }

}, 1000);

当你想要停止循环时,你可以简单地破坏计时器

clearInterval(timerId);
  

编辑:我已为插件添加了一个选项

$("#typed").typed({
    strings: ["Typed.js is a jQuery plugin.", "It types out sentences."],
    typeSpeed: 30,
    backDelay: 500,
    loop:true,
    callback: function(){ alert('end'); }
});

已编辑的插件文件

!function($){

    "use strict";

    var Typed = function(el, options){

        // for variable scope's sake
        self = this;

        // chosen element to manipulate text
        self.el = $(el);
        // options
        self.options = $.extend({}, $.fn.typed.defaults, options);

        // text content of element
        self.text = self.el.text();

        // typing speed
        self.typeSpeed = self.options.typeSpeed;

        // typing speed
        self.loop = self.options.loop;

        // amount of time to wait before backspacing
        self.backDelay = self.options.backDelay;

        // input strings of text
        self.strings = self.options.strings;

        // character number position of current string
        self.strPos = 0;

        // current array position
        self.arrayPos = 0;

        // current string based on current values[] array position 
        self.string = self.strings[self.arrayPos];

        // number to stop backspacing on.
        // default 0, can change depending on how many chars
        // you want to remove at the time
        self.stopNum = 0;

        // number in which to stop going through array
        // set to strings[] array (length - 1) to stop deleting after last string is typed
        self.stopArray = self.strings.length-1;

        // All systems go!
        self.init();
    }

        Typed.prototype =  {

            constructor: Typed

            , init: function(){
                // begin the loop w/ first current string (global self.string)
                // current string will be passed as an argument each time after this
                self.typewrite(self.string, self.strPos);
                self.el.after("<span id=\"typed-cursor\">|</span>");
            }

            // pass current string state to each function
            , typewrite: function(curString, curStrPos){

                // varying values for setTimeout during typing
                // can't be global since number changes each time loop is executed
                var humanize = Math.round(Math.random() * (100 - 30)) + self.typeSpeed;

                // ------ optional ------ //
                // custom backspace delay
                // if (self.arrayPos == 1){
                //  self.backDelay = 50;
                // }
                // else{ self.backDelay = 500; }

                // containg entire typing function in a timeout
                setTimeout(function() {

                    // make sure array position is less than array length
                    if (self.arrayPos < self.strings.length){

                        // start typing each new char into existing string
                        // curString is function arg
                        self.el.text(self.text + curString.substr(0, curStrPos));

                        // check if current character number is the string's length
                        // and if the current array position is less than the stopping point
                        // if so, backspace after backDelay setting
                        if (curStrPos > curString.length && self.arrayPos < self.stopArray){
                            clearTimeout();
                            setTimeout(function(){
                                self.backspace(curString, curStrPos);
                            }, self.backDelay);
                        }

                        // else, keep typing
                        else{
                            // add characters one by one
                            curStrPos++;
                            // loop the function
                            self.typewrite(curString, curStrPos);
                            // if the array position is at the stopping position
                            // finish code, on to next task
                            if (self.arrayPos == self.stopArray && curStrPos == curString.length){
                                // animation that occurs on the last typed string
                                // place any finishing code here

                                if(self.loop){
                                        self.arrayPos=0;
                                        curStrPos=0;
                                }else{
                                self.options.callback();
                                clearTimeout();}
                            }
                        }
                    }

                // humanized value for typing
                }, humanize);

            }

            , backspace: function(curString, curStrPos){

                // varying values for setTimeout during typing
                // can't be global since number changes each time loop is executed
                var humanize = Math.round(Math.random() * (100 - 30)) + self.typeSpeed;

                setTimeout(function() {

                        // ----- this part is optional ----- //
                        // check string array position
                        // on the first string, only delete one word
                        // the stopNum actually represents the amount of chars to
                        // keep in the current string. In my case it's 14.
                        // if (self.arrayPos == 1){
                        //  self.stopNum = 14;
                        // }
                        //every other time, delete the whole typed string
                        // else{
                        //  self.stopNum = 0;
                        // }

                    // ----- continue important stuff ----- //
                        // replace text with current text + typed characters
                        self.el.text(self.text + curString.substr(0, curStrPos));

                        // if the number (id of character in current string) is 
                        // less than the stop number, keep going
                        if (curStrPos > self.stopNum){
                            // subtract characters one by one
                            curStrPos--;
                            // loop the function
                            self.backspace(curString, curStrPos);
                        }
                        // if the stop number has been reached, increase 
                        // array position to next string
                        else if (curStrPos <= self.stopNum){
                            clearTimeout();
                            self.arrayPos = self.arrayPos+1;
                            // must pass new array position in this instance
                            // instead of using global arrayPos
                            self.typewrite(self.strings[self.arrayPos], curStrPos);
                        }

                // humanized value for typing
                }, humanize);   

            }

        }

    $.fn.typed = function (option) {
        return this.each(function () {
          var $this = $(this)
            , data = $this.data('typed')
            , options = typeof option == 'object' && option
          if (!data) $this.data('typed', (data = new Typed(this, options)))
          if (typeof option == 'string') data[option]()
        });
    }

    $.fn.typed.defaults = {
        strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
        // typing and backspacing speed
        typeSpeed: 0,
        // time before backspacing
        backDelay: 500,
        loop:false,
        // ending callback function
        callback: function(){ null }
    }


}(window.jQuery);

答案 2 :(得分:2)

$(func = function () {
      $(".element").typed({
          strings: ['Statement One', 
            'Satemante Two',
          'Statemante Three', ''],
          typeSpeed: 40, // typing speed
          backDelay: 2000,
          callback: function (){
            func();
          }
      });

  });

答案 3 :(得分:1)

试试这个:

$(".typed-text").typed({
    strings: ["test 1", "test 2", "test 3", "test 4"],
    typeSpeed: 10,
    backDelay: 1500,
    loop: !0, // here
    startDelay: 1000,
});

答案 4 :(得分:0)

你试过了吗?

var myFunc = function() {
  $("span.text-change").typed({
     strings: ["First sentence.", "Second sentence."],
     typeSpeed: 30, // typing speed
     backDelay: 500, // pause before backspacing
     callback: function () {
         myFunc();
     }
  });
}

答案 5 :(得分:0)

只需添加属性循环:1。无限循环

$(&#34; .typed文本&#34)。类型({     字符串:[&#34;测试1&#34;,&#34;测试2&#34;,&#34;测试3&#34;,&#34;测试4&#34;],     typeSpeed:10,     backDelay:1500,     循环:1,//这里 });