0

私はこれを行う方法を見つけようとしてきましたが、実際にはどこにも行きませんでした。ボタンをクリックすると下の関数を一時停止し、2 回目にクリックすると再び開始する必要があります。

var About = function(dom) {
    this.text_spans = $('li', dom);
    this.len = this.text_spans.length;
    this.index = 0;

    this.init();

}

$.extend(About.prototype, {
    interval: 2.5 * 1000,
    init: function() {
        var that = this;
        setTimeout(function() {
            that.text_spans.eq(that.index++ % that.len).removeClass('visible');
                that.text_spans.eq(that.index % that.len).addClass('visible');
            setTimeout(arguments.callee, that.interval);
        }, that.interval);
    }
});

この関数の目的は、一連のテキスト (たとえばli's) を非表示にし、無限にループバックすることです。ボタン/リンクをクリックすると、関数は一時停止し、テキストの変更を停止します。

clearTimeout() と関係があることは知っていsetTimeout()ますが、これを機能させるための構文や方法がよくわかりません。誰かがそれを理解するのを手伝ってくれますか? どうもありがとうございました :)

4

1 に答える 1

0

次のようなものを試してください ( demo ):

$.extend(About.prototype, {
    interval: 2.5 * 1000,
    init: function () {
        var that = this;
        $('a.toggle').click(function(){
            var running = $(this).hasClass('running');
            $(this).toggleClass('running', !running);
            if (running){
                clearInterval(that.timer);
            } else {
                that.timer = setInterval(function () {
                    that.text_spans.eq(that.index++ % that.len).removeClass('visible');
                    that.text_spans.eq(that.index % that.len).addClass('visible');
                }, that.interval);
            }
        }).click(); // start timer
    }
});

HTML

<a class="toggle" href="#">Click me to pause function</a>
于 2013-04-24T22:28:18.823 に答える