之前在“jQuery stop()方法的使用”这一节中,我们接触了 jQuery 动画中最常见的一个 bug,也和大家详细探讨了这个 bug 产生的根本原因以及解决方法。实际上,除了 stop() 方法,我们还可以使用 is() 方法来解决这个 bug。
在 jQuery 中,我们可以使用 is() 方法来判断元素是否正处于动画状态。如果元素不处于动画状态,则添加新的动画;如果元素正处于动画状态,则不添加新的动画。
语法:
:animated 是一个伪类选择器,表示选取所有正在执行动画的元素,我们在“其他伪类选择器”这一节中已经介绍过了。
举例:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- <style type="text/css">
- figure
- {
- position:relative; /*设置相对定位属性,以便定位子元素*/
- width:240px;
- height:200px;
- overflow: hidden;
- }
- img
- {
- width:240px;
- height:200px;
- }
- figcaption
- {
- position:absolute;
- left:0;
- bottom:-30px;
- width:100%;
- height:30px;
- line-height:30px;
- text-align:center;
- font-family:"微软雅黑";
- background-color:rgba(0,0,0,0.6);
- color:white;
- }
- </style>
- <script src="js/jquery-1.12.4.min.js"></script>
- <script>
- $(function () {
- $("figure").hover(function () {
- if (!$(">figcaption", this).is(":animated")) {
- $(">figcaption", this).animate({ "bottom": "0px" }, 200);
- }
- }, function () {
- if (!$(">figcaption", this).is(":animated")) {
- $(">figcaption", this).animate({ "bottom": "-30px" }, 200);
- }
- })
- })
- </script>
- </head>
- <body>
- <figure>
- <img src="img/ciri.png" alt="">
- <figcaption> 《巫师3》之希里</figcaption>
- </figure>
- </body>
- </html>
默认情况下,预览效果如图 1 所示。
当鼠标指针移到图片上时,预览效果如图 2 所示。
在这个例子中,$(">figcaption",this)表示选取当前元素下面的子元素 figcaption,它其实可以等价于$("figure>figcaption")。这种写法是 jQuery 的高级技巧,它其实借助了$()方法的第 2 个参数,当然我们之后会详细介绍。
此外,在实际开发中,is(":animated") 比 stop() 方法更加容易理解,也更加常用。