CSS/jQuery 动画未触发



我正在尝试使用动画,通过在页面加载时更改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>

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

$(function () {
    $('img').addClass("loaded");
});
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;
    }
}
<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" />

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

-webkit-animation: widthChange 3s forwards;

您可以尝试使用此所有浏览器都支持的代码: 小提琴

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;}
}
首先,

动画名称是一种实验性技术,您可以在此处查看: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

最新更新