jQuery animate()

Ana*_*ant 4 jquery jquery-animate

我的代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
#Layer1 {
 position:absolute;
 width:200px;
 height:115px;
 z-index:1;
 left: 445px;
 top: 64px;
}
-->
</style>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function toggle()

{

$("#Layer1").animate({width:"20px"},1000);

}
</script>
</head>

<body onload="toggle()">
<div id="Layer1"><img src="friend-line.jpg" width="243" height="380" /></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在,当页面加载时,最初会有一个动画,但很快就会恢复第1层的尺寸.我想知道为什么会发生这种情况.谢谢!

Pet*_*tai 8

动画添加了CSS的overflow:hidden时间.当它停止时,overflow会返回到之前的状态,所以你应该只是永久地添加overflow:hiddenCSS#Layer1

另外,我建议您使用jQuery doc ready功能而不是内联onloadJavascript.

所以你的整个JS将是:

$(function() { // <== doc ready
    $("#Layer1").css("overflow","hidden").animate({width:"20px"},1000);
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle例子


我不太确定你要用你的代码完成什么,但你也可以overflow:hidden在你的CSS中包含#Layer1:

#Layer1 {
 position:absolute;
 width:200px;
 height:115px;
 z-index:1;
 left: 445px;
 top: 64px;
 overflow:hidden;
}
Run Code Online (Sandbox Code Playgroud)

使用上面的CSS,您可以使用原始代码,只需将其包装在doc ready中,然后onload从HTML中删除:

$(function() { // <== doc ready
    $("#Layer1").animate({width:"20px"},1000);
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle例子

请注意,div的宽度小于图像的宽度.不确定这是否有意.