【问题标题】:How can I animate an element changing its opacity at the same time?如何为元素设置动画,同时改变其不透明度?
【发布时间】:2017-01-11 20:21:24
【问题描述】:

我希望一个元素制作一个从左到右的动画,将其不透明度从 0 更改为 1。

我已经为元素设置了动画,但我不能同时改变它的不透明度。

这是我目前拥有的代码:

$("#moveIt").animate({left:0, opacity:"show"}, 1500);
#moveIt{
  position: relative;
  left: 200px;
  height: 300px;
  width: 300px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moveIt">
  <span>This is the div that I want to move</span>
</div>

我知道JQuery 上有一个函数叫做fadeTo,但我不知道如何将它与animate 函数结合来改变不透明度元素的同时我为元素设置动画。

我可以用fadeTo 函数包装animate 函数,但它会在动画函数触发之前改变元素的不透明度,而不是同时,根据我的需要。

如何在设置动画的同时更改元素的opacity

提前致谢!

【问题讨论】:

    标签: jquery html css animation


    【解决方案1】:

    opacity 属性的取值范围为 0.0 - 1.0。

    http://www.w3schools.com/css/css_image_transparency.asp

    改变

    $("#moveIt").animate({left:0, opacity:"show"}, 1500);
    

    $("#moveIt").animate({left:0, opacity:1}, 1500);
    

    如果您想淡入,则在页面加载时使用 css 设置不透明度 0,并使用 .animate() 将其更改为 1

    $("#moveIt").animate({left:0, opacity: 1}, 1500);
    #moveIt{
      position: relative;
      left: 200px;
      height: 300px;
      width: 300px;
      background-color: red;
      opacity : 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="moveIt">
      <span>This is the div that I want to move</span>
    </div>

    【讨论】:

    • 谢谢!我没有注意到我可以更改 animate 函数上的 opacity 值。我现在感觉好傻……
    • NP :) 很高兴帮助 :)
    【解决方案2】:

    初始化不透明度。

    $("#moveIt").animate({left:0, opacity: 1}, 1500); // set opacity to 1
    #moveIt{
      position: relative;
      left: 200px;
      height: 300px;
      width: 300px;
      background-color: red;
      opacity : 0; /* opacity to zero */
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="moveIt">
      <span>This is the div that I want to move</span>
    </div>

    【讨论】:

    • 感谢您的回答。这正是我正在寻找的,但我最终认为@Deep 的答案更完整。 +1 顺便说一句
    【解决方案3】:

    您可以将 .animate() 替换为更 CSS 的解决方案。

    示例:

    $(document).ready(function() {
      $("#moveIt").addClass('animate');
    });
    .element {
      position: relative;
      left: 200px;
      height: 300px;
      width: 300px;
      background-color: red;
      transition: all 1.5s; /* change speed here (1.5s)*/
      opacity: 0;
    }
    
     /* Values to animate to */
    .animate {
      opacity: 1;
      left: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="moveIt" class='element'>
      <span>This is the div that I want to move</span>
    </div>

    【讨论】:

      猜你喜欢
      • 2011-01-22
      • 2013-07-17
      • 2018-09-13
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      相关资源
      最近更新 更多