我正在尝试以下代码:
$(document).ready(function() {
$("button").hover(
function() {
$(this).addClass("active");
},
function() {
$(this).removeClass("active");
}
);
});
答案 0 :(得分:2)
尝试一下:http://plnkr.co/edit/Xlco44QPWvKEh1jb0gDf?p=preview
setTimeout
根据您在下面的上一条评论中所述,您尝试了this
,但由于您使用this
的方式而无法使用。超时函数中的setTimeout
的值与外部函数中的值不同,因此jQuery与您的按钮元素不匹配。
最好一次将按钮定义为一个变量,然后使用重复的jQuery选择器重复使用该变量。
更新:这是一个稍微复杂一些的版本,可防止$(function() {
var button = $('button');
var timeout = 0;
button.hover(
function() {
button.addClass('active');
timeout = setTimeout(function() {
button.removeClass('active');
timeout = 0;
}, 2000);
},
function() {
button.removeClass('active');
if (timeout) {
clearTimeout(timeout);
timeout = 0;
}
}
);
});
计时器堆积:
onResponse
答案 1 :(得分:-1)
我为此专门创建了一个 jQuery 扩展!这在Web开发中非常普遍:
$.fn.addTempClass = function(tempClass, duration){
if( !tempClass )
return this;
return this.each(function(){
var $elm = $(this),
timer;
$elm.addClass(tempClass);
// clear any timeout, if was any
clearTimeout( $elm.data('timeout') )
timer = setTimeout(function(){
$elm.removeClass(tempClass).removeData('timeout');
}, duration || 100);
// set the timer on the element
$elm.data('timeout', timer);
});
};
$(document.body).addTempClass('some_class', 2000)
您可以将此脚本作为构建系统的依赖文件包括在内,也可以在加载 jQuery 之后将该代码片段复制粘贴到您的代码中的某个位置,以便以后在任何地方都可以使用。