2015-04-24 125 views
2

我試圖使用動畫,通過在頁面加載中更改jQuery中的類觸發。目前它沒有做任何事情。我不確定發生了什麼問題,雖然我很確定它的CSS有問題。這裏是我的代碼:CSS/jQuery動畫不觸發

<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> 

回答

1

你可以使用此代碼是由所有的瀏覽器支持的嘗試: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

您需要定義供應商前綴(在寫作的時間),WebKit瀏覽器,看到support information。正確的定義是這樣的:

$(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;

​​