如何停止多次单击下一个以破坏我的图像旋转器
How do I stop clicking next too many times from breaking my image rotator?
我是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) );
相关文章:
- 当按下箭头键时,我的图像以一种奇怪的方式跳跃(HTML+JS)
- 如何在PHP中使用url保护我的图像和文件夹免受直接访问
- 当我使用JS/jQuery/any插件点击图像时,我如何使背景变暗+不可点击,并放大和居中我的图像
- 如果我将宽度调整为另一个值,找出我的图像的高度
- 为什么我的图像幻灯片不起作用
- 将下一个和上一个按钮添加到我的图像滑块
- 按键缩放我的图像
- 咕哝:咕哝rev任务通过添加随机哈希来更改我的图像,从而阻止我的html识别它们
- 如何移动我的图像's的位置
- 为什么我的图像高度没有改变
- 如何停止多次单击下一个以破坏我的图像旋转器
- 制作一个简单的JavaScript滑块,我将如何为我的图像添加描述
- 我的图像幻灯片代码有什么问题
- 调整图像大小以使其完美地适合幻灯片,问题仍然是用 for 循环将 CSS 代码替换为我的图像
- 为什么我无法让我的图像出现在表格单元格/节点中.也许我可以得到一些结束
- 如何让不同的图像和文本自动循环浏览?我的图像正在循环,但我的文本不是
- 将 JavaScript 计数器添加到我的图像中
- 如何在我的图像上添加叠加层
- HTML5画布正在调整我的图像大小
- 我的图像替换需要更多帮助,将数组对象添加为类