如何停止多次单击下一个以破坏我的图像旋转器

How do I stop clicking next too many times from breaking my image rotator?

本文关键字:我的 图像 旋转 一个以 何停止 单击 下一个      更新时间:2023-09-26

我是jquery的新手,并且一直在尝试编写一个简单的图像旋转器,它目前运行良好,除了如果您单击"prev"按钮的"下一步"太多次非常快,它会破坏图像旋转器。

这是 html:

<div id="viewport">
    <div id="imageContainer">
        <div class="image" style="background-color:red;">
            <div class="title"><p>This is the title of the post</p></div>
        </div>
        <div class="image" style="background-color:green;">
            <div class="title"><p>This is the title of the post</p></div>
        </div>
        <div class="image" style="background-color:yellow;">
            <div class="title"><p>This is the title of the post</p></div>
        </div>
        <div class="image" style="background-color:brown;">
            <div class="title"><p>This is the title of the post</p></div>
        </div>
        <div class="image" style="background-color:purple;">
            <div class="title"><p>This is the title of the post</p></div>
        </div>
    </div>
</div>
<input type="button" name="prev" id="prev" value="prev" />
<input type="button" name="next" id="next" value="next" />

和jquery:

var ic = $('#imageContainer');
    var numItems = $('.image').size();
    var position = 0;
    ic.css('left', '0px');
    var inter; 
    var rotateTimeout;
    function rotate(){
        inter = setInterval(function(){
             if (position == (numItems - 1)) {
                console.log(position);
                $('.image').first().insertAfter($('.image').last());
                ic.css('left', '+=400px');
                position--;
            }
            ic.animate({opacity: 0.2, left: "-=400px"}, 1500, function(){
                ic.animate({opacity: 1.0}, 1000);
            });
            position += 1;
        }, 6000);
    }
    rotate();
    $('#prev').click(function () {
        console.log(position);
        if (position == 0) {
            $('.image').last().insertBefore($('.image').first());
            ic.css('left', '-=400px');
            position++;
        }
        ic.animate({
            left: "+=400px"
        });
        position -= 1;
        clearInterval(inter);
        clearTimeout(rotateTimeout);
        rotateTimeout = setTimeout(rotate, 10000);

    });
    $('#next').click(function () {
        if (position == (numItems - 1)) {
            console.log(position);
            $('.image').first().insertAfter($('.image').last());
            ic.css('left', '-400px');
            position--;
        }
        ic.animate({
            left: "-=400px"
        });
        position += 1;
        clearInterval(inter);
        clearTimeout(rotateTimeout);
        rotateTimeout = setTimeout(rotate, 10000);

    });

这是旋转器的演示。

那么,我怎样才能阻止用户过快地点击按钮,或者可能只考虑每两秒点击一次,以允许旋转器做它需要的事情呢?

要限制函数调用频率,您可以使用一些"油门"函数。例如,来自 Underscore .js 或任何其他实现的_.throttle。没有必要使用整个库,只能从那里复制所需的功能。

事件处理程序附件将如下所示:

$('#prev').click( _.throttle(function () { yours code... }, 2000) );