2011-09-19 107 views
11

我已經找到了這個答案,我發現它,但我不知道如何使用它。動畫上懸停gif

Stop a gif animation onload, on mouseover start the activation

Guffa的回答這個問題正是我想要的,但我不知道如何使用這些代碼。

我有jquery插件,但是我在哪裏放置代碼(不是插件;代碼是在Guffa的答案中)?如何參照圖像使用它?是否有一個函數需要調用才能使其正常工作?如果是這樣,那麼稱呼它的最好方法是什麼?

不好意思問一個已經回答了的問題,但是他的回答不夠具體,我不能評論問他一個更具體的答案。

回答

17

這裏是你所需要的工作的例子 - http://jsfiddle.net/EXNZr/1/

<img id="imgDino" src="http://bestuff.com/images/images_of_stuff/64x64crop/t-rex-51807.jpg?1176587870" /> 

<script> 
    $(function() { 
     $("#imgDino").hover(
      function() { 
       $(this).attr("src", "animated.gif"); 
      }, 
      function() { 
       $(this).attr("src", "static.gif"); 
      }       
     );     
    }); 
</script> 
+0

好的,非常感謝。但是,如果我是你,我只是把腳本標籤內的jQuery。但是,謝謝,我會接受這個答案。哦,你鏈接的網站是非常有用的,我不相信我還沒有看到。 –

+1

確保你預載了GIF動畫,否則它們可能會延遲翻滾。或者更好的是,使用動畫gif上方的靜態gif製作一個gif,將gif設置爲元素的背景圖像,並簡單地更改翻轉(也稱爲CSS sprite翻轉)的背景定位。 – Tim

4

我沒有看過的鏈接,但是要做到這一點是改變使用JavaScript的img標籤src屬性懸停像這樣(jQuery的)需要

$(function() { 
    $('a').hover(function() { 
     $(this).attr('src','path_to_animated.gif'); 
    },function() { 
     $(this).attr('src','path_to_still.gif'); 
    } 
}); 

無插件最簡單的方法......你可能希望通過在懸停綁定之前添加$('<img />',{ src: 'path_to_animated.gif'});來預加載動畫gif。

希望幫助

+0

確實如此,但是這對於guffa的問題非常相似的答案是我不知道該怎麼處理該代碼。這是我需要調用的函數嗎?我在哪裏放?告訴我它將如何在HTML文檔 –

+0

@Mark Kramer中起作用,哪些位不理解? – ianbarker

0

試試這個,如果你即可使用帆布:

<!DOCTYPE html> 
    <html> 
    <head> 
     <style> 
      .wrapper {position:absolute; z-index:2;width:400px;height:328px;background-color: transparent;} 
      .canvas {position:absolute;z-index:1;} 
      .gif {position:absolute;z-index:0;} 
      .hide {display:none;} 
     </style> 

     <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 

     <script> 
      window.onload = function() { 
       var c = document.getElementById("canvas"); 
       var ctx = c.getContext("2d"); 
       var img = document.getElementById("gif"); 
       ctx.drawImage(img, 0, 0); 
      } 

      $(document).ready(function() { 
       $("#wrapper").bind("mouseenter mouseleave", function(e) { 
        $("#canvas").toggleClass("hide"); 
       }); 
      }); 
     </script> 

    </head> 
    <body> 

    <div> 
     <img id="gif" class="gif" src="https://www.macobserver.com/imgs/tips/20131206_Pooh_GIF.gif"> 

     <canvas id="canvas" class="canvas" width="400px" height="328px"> 
     </canvas> 

     <div id="wrapper" class="wrapper"></div> 
    </div> 

    </body> 
    </html>