jQuery中的反跳功能? [英] Debounce function in Jquery?

查看:125
本文介绍了jQuery中的反跳功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Jquery中寻找反跳功能或反跳方式。动画的构建会变得非常烦人。
此处为代码:

Been looking for a debounce function or way to debounce in Jquery. The build up of animations can get super annoying. Heres the code:

function fade() {
    $('.media').hide();
    $('.media').fadeIn(2000);
}
var debounce = false;
function colorChange() {

    if (debounce) return;
    debounce = true;
    $('.centered').mouseenter(function() {
    $('.centered').fadeTo('fast', .25);
    });
    $('.centered').mouseleave(function() {
    $('.centered').fadeTo('fast', 1);
});
}

 function colorChange2() {
    $('.centered2').mouseenter(function() {
    $('.centered2').fadeTo('fast', .25);
});
$('.centered2').mouseleave(function() {
    $('.centered2').fadeTo('fast', 1);
});
}

function colorChange3() {
$('.centered3').mouseenter(function() {
    $('.centered3').fadeTo('fast', .25);
});
$('.centered3').mouseleave(function() {
    $('.centered3').fadeTo('fast', 1);
});
}

function closerFade() {
    $('.closer').hide();
    $('.closer').fadeIn(2000);
}

我将它们全部包裹在$(document).ready(function(){

I wrapped those all in $(document).ready(function() {

是否可以消除抖动?

推荐答案

我只是想在我的项目中包含underscore.js并使用它包含的debounce函数。它很好用。我已在多个项目中使用它。

I would just include underscore.js in my project and use the debounce function that it contains. It works great. I've used it in multiple projects.

http://underscorejs.org/#debounce


debounce_.debounce(function,wait,[immediate])(创建并返回已传递函数的
新反跳版本,该函数会将
的执行推迟到等待毫秒后执行)自上次调用
以来已经过去了。对于实现仅在输入停止到达后才出现
的行为非常有用。例如:渲染Markdown注释的
预览,重新计算窗口
停止调整大小后的布局,等等。

debounce_.debounce(function, wait, [immediate]) Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

在等待间隔结束时,将使用最近传递给去抖动功能的
参数调用该函数。

At the end of the wait interval, the function will be called with the arguments that were passed most recently to the debounced function.

为直接参数传递true会导致反跳触发在等待
间隔的前缘而不是后沿触发
函数。在防止意外的
双击提交按钮第二次触发的情况下很有用。

Pass true for the immediate argument to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);


这篇关于jQuery中的反跳功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆