之前在“jQuery動畫的停止”這一節中,我們接觸過jQuery動畫中最常見的一個小bug。也詳細給大家探討了這個bug出現的根本原因以及解決方法。
除了stop()方法,在jQuery中我們還可以使用is()方法來判斷所選元素是否正處於動畫狀態,如果元素不處於動畫狀態,則添加新的動畫;如果元素處於動畫狀態,則不添加新的動畫。
語法:
if(!$().is(":animated"))
{
//如果當前沒有進行動畫,則添加新動畫
}
說明:
這個判斷方法在jQuery動畫中經常被用到,大家要認真留意一下。
舉例:
在線測試
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
#wrapper
{
position:relative; /*設置相對定位屬性,以便定位子元素*/
width:240px;
height:200px;
overflow:hidden;
}
img
{
width:240px;
height:200px;
}
#content
{
position:absolute;
left:0;
bottom:-28px;
width:100%;
height:28px;
line-height:28px;
font-family:微軟雅黑;
text-align:center;
background-color:rgba(0,0,0,0.7);
color:White;
}
</style>
<script type="text/javascript" src="../App_js/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(function () {
$("#wrapper").hover(function () {
if(!$(" #content", this).is(":animated"))
{
$(" #content", this).animate({ "bottom": "0px" }, 200);
}
}, function () {
if(!$(" #content", this).is(":animated"))
{
$(" #content", this).animate({ "bottom": "-28px" }, 200);
}
})
})
</script>
</head>
<body>
<div id="wrapper">
<img src="../App_images/lesson/run_jq/nvdi.png" alt=""/>
<div id="content">海賊王女帝</div>
</div>
</body>
</html>
在浏覽器預覽效果如下:
分析:
在實際開發中,is(":animated")比stop()方法更加容易理解,也更加常用。