简体   繁体   English

jQuery中的可暂停打字机效果

[英]Pausable typewriter effect in jQuery

I'm using the typewriter plugin from Jason Frame's Grab Bag . 我正在使用Jason Frame的Grab Bag中的打字机插件。

However, I now find myself in a situation where I need to be able to pause and resume this typewriter at any point during its run. 但是,我现在发现自己处于这样一种情况,我需要能够在运行过程中的任何时候暂停并恢复该打字机。

Ideally, I'd have .typewriter("pause") to pause it, and .typewriter("resume") to resume the animation from where it left off. 理想情况下,我需要.typewriter("pause")暂停它,并使用.typewriter("resume")从停止的地方恢复动画。

I've tried setting a paused variable within the plugin, and leaving the interval running with a check for the variable each iteration -- if true, do nothing. 我尝试在插件中设置一个paused变量,并在每次迭代时都对变量进行检查以保持间隔运行-如果为true,则不执行任何操作。

However, due to my lack of skills in making jQuery plug-ins, each time I call the function to pause the typewriter, it just starts all over again. 但是,由于我缺乏制作jQuery插件的技能,所以每次我调用该函数来暂停打字机时,它都会重新开始。 I suspect the paused variable gets reset. 我怀疑paused变量会重置。

How would I go about making this plugin pausable? 我将如何使该插件可暂停?

jsBin demo jsBin演示

Add this 2 lines here: 在此处添加这2行:

(function($) {      
    $.fn.typewriter = function() {
        this.each(function() {
            var $ele = $(this), str = $ele.text(), progress = 0;
            $ele.text('');
            timer = setInterval(function() {
              if(pause===false){    // ADD THIS LINE ////////////////////////
                  $ele.text(str.substring(0, progress++) + (progress & 1 ? '_' : ''));
                  if (progress >= str.length) clearInterval(timer);
              }                     // ADD THIS LINE ////////////////////////
            }, 100);
        });
        return this;
    };   
})(jQuery);

$("#typewriter").typewriter(); // run your plugin

and I created this: 我创建了这个:

var pause = false;
$('#play_pause').click(function(){
  pause= !pause ? true : false;    // toggle true/false pause states
});

EDIT: find a better plugin-like solution in the comment below! 编辑:在下面的评论中找到更好的类似于插件的解决方案!

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

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