animate() 和 fadeIn() 无法按预期工作

Posted

技术标签:

【中文标题】animate() 和 fadeIn() 无法按预期工作【英文标题】:animate() and fadeIn() not working as desired 【发布时间】:2014-08-03 18:01:46 【问题描述】:

我希望第三个 div 在它淡入时移动到第三个 div 内,但是,因为它的位置是绝对的,所以它的位置是正确的。请为这个问题提出一个解决方案。我还想要同时的淡入淡出和动画效果,但代码没有按预期工作。请帮忙!

<html>
 <head>
    <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript" charset="UTF-8"></script>
<script src="animation.js"></script>
<link rel="stylesheet" type="text/css" href="req.css">
 </head>
 <body>
 <div class="one"><button class="b">Click Me!</button></div>
 <div class="two"></div>
 <div class="three">
    <div class="three1 anim" style="position:absolute;"></div>
        <div class="three2 anim"></div>
        <div class="three3 anim"></div>
 </div>
 </body>
 </html>

jquery 和 css 代码如下:

one
    height: 100%;
width: 400px;
background: rgb(241, 196, 15);
float:left;

.two
height: 100%;
width: 400px;
background: rgb(230, 126, 34);
float:left;

.three
height: 100%;
width: 400px;
background: rgb(231, 76, 60);
float:left;

.three1
height: 100px;
width: 350px;
margin-left: 25px;
margin-right: 25px;
margin-top:15px;
background: rgb(26, 188, 156);
float:left;
postion:absolute;
display:none;

.three2
height: 100px;
width: 350px;
margin-left: 25px;
margin-right: 25px;
margin-top:15px;
background: rgb(46, 204, 113);
float:left;
postion:absolute;
display:none;

.three3
height: 100px;
width: 350px;
margin-left: 25px;
margin-right: 25px;
margin-top:15px;
background: rgb(52, 152, 219);
float:left;
postion:absolute;
display:none;

JQuery:

$(document).ready(function()
    $('.b').click(function()
        $('.anim').fadeIn(2000);
    $('.anim').animate(left:'100px');
    );
);

【问题讨论】:

【参考方案1】:

你可以做到这一点,

$('.anim').animate('opacity':1,'left':'100px',2000);

由于您在同一个元素上使用动画,第二个动画将被排队,因此您不能同时运行这两个动画。

【讨论】:

【参考方案2】:

fadeIn 和 animate 不会同时运行,它们会排队。如果我从头开始编写,我不会这样做,但调整代码的最简单方法是:

摆脱显示:CSS 中的无 将其换成不透明度:0 然后将您的 jQuery 调整为如下所示

jQuery:

$('.anim').animate(left:'100px', opacity: '1',2000);

这是一个带有我修改过的代码的 jsFiddle

http://jsfiddle.net/Wrx2k/

另外,只是一个小指针,你的 position: absolute 在 CSS 样式中有一个错字。此外,尽量避免同时使用样式表和内联 CSS 来实现可管理的样式。

【讨论】:

以上是关于animate() 和 fadeIn() 无法按预期工作的主要内容,如果未能解决你的问题,请参考以下文章

同时运行两个动作,fadein() & animate() [重复]

如何避免在 jQuery 动画 [fadeIn() 或 animate()] 结束时出现文本闪烁?

jquery fadeIn 是如何工作的?用 animate() 做同样的事情

自定义动画animate()

animate.css动画初始状态隐藏

webpack中使用wowjs和animate.css