CSS / jQuery动画不会触发

时间:2015-04-24 21:11:42

标签: javascript jquery html css animation

我正在尝试使用动画,通过在页面加载时更改jQuery中的类来触发。它目前没有做任何事情。我不确定出了什么问题,虽然我很确定CSS有问题。这是我的代码:

<html> 

  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
    <title>Page 2</title>

    <style type="text/css">
    /* Your styles go here */
    img {width:200px; height:100px; animation-name: widthChange; animation-duration: 3s;}
    .loaded {animation-name: widthChange; animation-duration: 3s;}
    p {text-align:center}
    button {margin:20px}

    @keyframes widthChange {
        from {width: 200px;}
        to {width: 400px;}
    }

    </style>

    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
       // jQuery methods go here...
       $(document).ready(function() {
        $('img').addClass("loaded");
       });

    });
    /* Your additional JavaScript goes here */
    </script>
  </head>

  <body>
    <img class = "image" src="elephant.jpg" alt="elephant"/>
    <p><button>Button 1</button><button>Button 2</button><button>Button 3</button></p>

  </body>
</html>

3 个答案:

答案 0 :(得分:2)

您需要为webkit浏览器定义供应商前缀(在撰写本文时),请参阅support information。正确的定义如下所示:

&#13;
&#13;
$(function () {
    $('img').addClass("loaded");
});
&#13;
img {
    width:200px;
    height:100px;
}
.loaded {
    -webkit-animation: widthChange 3s;
    animation: widthChange 3s;
}
p {
    text-align:center
}
button {
    margin:20px
}
@-webkit-keyframes widthChange {
    from {
        width: 200px;
    }
    to {
        width: 400px;
    }
}
@keyframes widthChange {
    from {
        width: 200px;
    }
    to {
        width: 400px;
    }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="image" src="http://lorempixel.com/100/100" alt="elephant" />
&#13;
&#13;
&#13;

如果您希望图片在动画结束后保留​​最终状态,则可以添加animation-fill-mode: forwards;

-webkit-animation: widthChange 3s forwards;

答案 1 :(得分:1)

You could try with this code that is supported by all browsers: fiddle

img {
    width:200px; 
    height:100px; 
    animation-name: widthChange; 
    animation-duration: 3s;
    -webkit-animation-name: widthChange; 
    -webkit-animation-duration: 3s;
    -moz-animation-name: widthChange; 
    -moz-animation-duration: 3s;
    -0-animation-name: widthChange; 
    -0-animation-duration: 3s;    
}
p {text-align:center}
button {margin:20px}

@-webkit-keyframes widthChange {
    from {width: 200px;}
    to {width: 400px;}
}
@-o-keyframes widthChange {
    from {width: 200px;}
    to {width: 400px;}
}
@-moz-keyframes widthChange {
    from {width: 200px;}
    to {width: 400px;}
}
@keyframes widthChange {
    from {width: 200px;}
    to {width: 400px;}
}

答案 2 :(得分:0)

首先,动画名称是一项实验性技术,您可以在此处查看: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name

其次,每个动画都需要您在代码中没有的关键帧,您可以尝试使用css过渡:https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions