在悬停时动画gif

Mar*_*mer 12 javascript jquery animation gif

我找到了答案,我找到了,但我不知道如何使用它.

停止gif动画onload,在mouseover上启动激活

Guffa对这个问题的回答正是我想要的,但我不知道如何使用该代码.

我有jquery插件,但我在哪里放置代码(不是插件; Guffa的答案中的代码)?如何在参考图像时使用它?是否有一个功能我必须打电话让它工作?如果是这样,最好的方法是什么?

很抱歉提出一个已经回答的问题,但他的答案不够具体,我无法发表评论,要求他提供更具体的答案.

Ami*_*mit 22

以下是您需要的工作示例 - 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>
Run Code Online (Sandbox Code Playgroud)

  • 确保你预加载GIF动画,否则它们可能会延迟翻转.或者更好的是,使用动画gif上方的静态gif创建一个gif,将gif设置为元素的背景图像,并简单地更改rollover上的背景定位(也称为CSS sprite rollovers). (2认同)

ian*_*ker 6

我还没有阅读链接,但是最简单的方法是像这样在悬停时使用 javascript 更改 img 标签 src 属性(jQuery)

$(function() {
    $('a').hover(function() {
      $(this).attr('src','path_to_animated.gif');
    },function() {
      $(this).attr('src','path_to_still.gif');
    }
});
Run Code Online (Sandbox Code Playgroud)

不需要插件...您可能希望通过$('<img />',{ src: 'path_to_animated.gif'});在悬停绑定之前添加来预加载动画 gif 。

希望有帮助


sun*_*nny 5

如果您可以使用画布,请尝试以下操作:

   <!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>
Run Code Online (Sandbox Code Playgroud)