jquery - 使用 jquery 在每次单击时向 div 添加/删除类

标签 jquery html css

我需要在单击时向“div”添加一个类,用于 CSS3 动画。但我还要求在动画结束后删除该类。

我尝试过类似的方法,但它不起作用 -

$('.class').click(function() {
    $('.class').removeClass("animate");
    $(this).addClass("animate");
});

请帮忙,谢谢。

最佳答案

您有两个直接的可能性:

1) 使用在动画完成后触发的 setTimeout 函数。为此,您应该知道动画持续时间有多长:

$('.class').click(function() {
    var animDuration = 1000; //ms of the animation duration
    $(this).addClass("animate");
    setTimeout(function(){
       $(this).removeClass("animate");
    }, animDuration);
});

2) 更好的解决方案是在 animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd 上添加一个事件监听器,它会在动画真正完成时触发。对于这种方法,您不需要知道动画的持续时间。

编辑:来自 adeneo 以及一些来自 here 的代码:

$('.class').click(function() {
    var animDuration = 1000; //ms of the animation duration
    $(this).addClass("animate");
    $(this).bind('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function () {
       $(this).removeClass('animate');
    });
});

上面的代码几乎完成了您所说的“动态获取持续时间”。它真正做的是监听动画完成/完成时触发的事件。多个事件监听器的原因是因为浏览器兼容性,每个浏览器都会触发自己的事件。 (oAnimationEnd = Opera,MSAnimationEnd = IE 等)

感谢:https://coderwall.com/p/hn7gsg

关于jquery - 使用 jquery 在每次单击时向 div 添加/删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19492336/

相关文章:

html - 可通过键盘导航的纯文本 HTML 单选按钮?

javascript - 如何更模块化地编写 jQuery 代码?

javascript - 通过 jQuery 检索并显示特定值

html - 以像素为单位设置 CSS font-size 时,该值是指字母的宽度还是高度?

jquery - 如何使用 jQuery 获取 html 表的最后一个可见子表行?

javascript - 如何通过 XMLHttpRequest 加载数据来填写 AngularJS 表单

html - 悬停一个 div 时更改两个元素

javascript - jQuery:获取内联样式而不是 body 的 CSS

javascript - Date.parse() 在 Mozilla Firefox JavaScript 中无法正常工作

html - 居中时仅在最后一行文本下划线