Animating a gif on hover

后端 未结 3 1800
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 11:44

I\'ve looked for the answer for this and I found it, but I don\'t know how to use it.

Stop a gif animation onload, on mouseover start the activation

Guffa\'s

相关标签:
3条回答
  • 2020-12-05 12:05

    Here is a working example for what you need - 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 讨论(0)
  • 2020-12-05 12:05

    I haven't read the link, however the easiest way to do this is to change the img tags src attribute with javascript on hover like this (jQuery)

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

    No plugins required... you might want to preload the animated gif by adding $('<img />',{ src: 'path_to_animated.gif'}); before the hover bind.

    Hope that helps

    0 讨论(0)
  • 2020-12-05 12:07

    Try this if you are OK to use canvas:

       <!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>
    
    0 讨论(0)
提交回复
热议问题