2015-10-13 82 views
1

我試圖加載編程img.gif擴展。但動畫只發生一次。動態地添加一個GIF圖像動畫

如何添加更多img並在每次添加新的img時看到動畫,而不僅僅是最終狀態?

注意:我不想要循環gif。我只想讓下一個img表現得像第一個一樣,然後停止動畫。

var topval = 10; 
 
var right = 10; 
 

 
var addStar = function() { 
 
\t var img = $('<img id="'+topval+'">'); 
 
\t img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif'); 
 
\t img.attr('alt','alt'+topval); 
 
\t img.css('position','absolute'); 
 
\t img.css('right', right+'px'); 
 
\t img.css('top', topval+'px'); 
 
\t img.appendTo('body'); 
 

 
\t topval = topval+10; 
 
\t right = right+10; 
 
}; 
 
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<body style="margin:0;padding:0;"> 
 
    <button id="addStar">Click do add</button> 
 
</body>

在此先感謝。

+2

你描述的在Chrome和Safari發生,但Firefox每次重新播放動畫。 – joews

+0

如何讓它在Chrome和Safari瀏覽器中運行?我需要在css中設置smth嗎? –

回答

1

你的問題是因爲瀏覽器採用相同的緩存圖像。當您更改圖片的網址時,就像您在尋找其他圖片一樣。這個缺點是他總是對圖像提出新的要求。

var topval = 10; 
 
var right = 10; 
 

 
var count = 0; 
 

 
var addStar = function(){ 
 
\t var img = $('<img id="'+topval+'">'); 
 
\t img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?count='+count++); 
 
\t img.attr('alt','alt'+topval); 
 
\t img.css('position','absolute'); 
 
\t img.css('right', right+'px'); 
 
\t img.css('top', topval+'px'); 
 
\t img.appendTo('body'); 
 

 
\t topval = topval+10; 
 
\t right = right+10; 
 
} 
 
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<body style="margin:0;padding:0;"> 
 
    <button id="addStar">Click do add</button> 
 
</body>

+0

缺點是我不存在,因爲圖像是從本地而不是像片段的遠程!謝謝! !!這是一個很好的解決方法 –

0
  1. 創建一個div
  2. 設置你的GIF格式圖片作爲DIV的背景圖像

    $('myDiv').css('background-image', 'url(' + imageUrl + ')');

+0

沒有爲我工作,如果爲你工作,請張貼一段。 :( –

+0

你有沒有Photoshop? 如果你這樣做,你可以編輯gif循環選項:去窗口>時間軸,然後選擇循環選項(左下角),另存爲網頁gif和voilá – javaguest

+0

感謝您的提示,但我真的不想要一個循環的gif,感謝tho –

1

您可以通過添加一個隨機的查詢字符串解決此問題破解參數到URL。這誘使瀏覽器認爲每次圖像都不一樣。例如:

https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?x=' + Math.random()

var topval = 10; 
 
\t var right = 10; 
 

 
var addStar = function(){ 
 
\t  \t var img = $('<img id="'+topval+'">'); 
 
\t  \t img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?x=' + Math.random()); 
 
\t  \t img.attr('alt','alt'+topval); 
 
\t  \t img.css('position','absolute'); 
 
\t  \t img.css('right', right+'px'); 
 
\t  \t img.css('top', topval+'px'); 
 
\t \t img.appendTo('body'); 
 

 
\t \t topval = topval+10; 
 
\t \t right = right+10; 
 
    } 
 
    $("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<body style="margin:0;padding:0;"> 
 
    <button id="addStar">Click do add</button> 
 
</body> 
 

 
Thanks in advance.

+0

haha​​hahah這是值得學習的smth!謝謝這個破解! –