我有一个问题。我刚开始学习 jQuery,这是我第一次接触 javascript。我想让一个元素在点击时具有动画效果,我确实做到了:
HTML:
<h1>Testing</h1>
我正在使用 Animate.css 使一些动画在点击时发生。这是我的 jQuery:
$('h1').click(function (e) {
$('h1').addClass('animated bounce');
});
我想要实现的是,当我点击第二次时,动画再次发生,实际上,我想删除 animated bounce 类并再次添加它,这样动画就会发生再次。
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<h1>Testing</h1>
<script>
$('h1').click(function (e) {
$('h1').addClass('animated bounce');
});
</script>
</body>
请告诉我我是否按照应有的方式编写代码,我的意思是如果语法没问题,我见过带有 $(this) 的代码,但我没有确定那是什么,我也看到类似 .on('click')
谢谢。
最佳答案
动画结束后,您需要删除 CSS 类。
$('h1').click(function() {
$(this).addClass('animated bounce').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$(this).removeClass();
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<h1>Testing</h1>
对于其余部分,您的语法没问题。
一些注意事项:
e
是一个基于 Event 的对象,描述已发生的事件。它是可选的。如果您不需要事件中的数据,可以跳过它。$(this)
是一个 jQuery 对象。在回调的上下文中,它是调用函数的元素。在 JavaScript 中,this
关键字是一个非常重要且复杂的主题。您可以在 MDN 中阅读相关信息在这里 SO .one()
是一个事件处理程序附加程序,可确保处理程序仅执行一次。on()
是其他附件。看看this other SO question了解何时使用click()
或on('click')
。
关于javascript - jQuery - 多次点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53181708/