jquery - 在 mouseenter 上浏览数组中的一组图像

标签 jquery css

我正在尝试在鼠标输入图像时制作“sprite 类动画”。我们的想法是让图像在悬停时“眨眼”一次。

我正在尝试这样做:

$(document).ready(function(){

   var images = [];
   images[0] = "images/image0.png";
   images[1] = "images/image1.png";
   images[2] = "images/image2.png";
   images[3] = "images/image3.png";
   images[4] = "images/image4.png";

   var count = 5;

   $("img.talk-to-us").mouseenter(function(){
      count = 0;
   });

   if(count < 5) {
      $("img.talk-to-us").attr("src",images[count]).delay(1000);
   count++;
   }
});

我希望在 mouseenter 上发生的是图像按顺序更改,每个图像之间有一个延迟。在最后一张图片之后我希望它停止(最后一张图片保持显示)。

关于如何使这项工作有任何想法吗? 谢谢!

最佳答案

这可能是适合您的方法:

$("img").mouseenter(function () {
    (function srcLoop(i) { // define a function (see IIFE)
        setTimeout(function () {
            $("img").attr("src", images[i]); //change the image src
                if (i > 0) {
                    i--; //decrement the counter
                    srcLoop(i); //recursivly call the function
                }
            }, 1000) //delay the function
    })(images.length - 1); //pass the length of the image-array as an argument (-1 because of the index starting at 0)
});

Demo

引用

.setTimeout()

IIFE - Immediatly Invoked Function Expression

关于jquery - 在 mouseenter 上浏览数组中的一组图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28943428/

相关文章:

php - 带有 Bootstrap 的 eldarion ajax

javascript - 仅捕获 src 标签中 '~' 之后的 6 个数字 javascript - 正则表达式

javascript - 单击按钮时显示框阴影的 Div

javascript - 给子元素添加悬停效果css/jquery

html - 获取 inset box-shadow 以覆盖包含 div 中的文本?

html - 左边是表格,右边是图片的列没有响应

javascript - 格式化 AJax 调用返回的 Json 并将其分配给 javascript 变量

javascript - 如何从有效控件中禁用 bootstrap 4 验证样式

javascript - 在jquery中设置item的值

javascript - 事件选项卡下的 CSS 箭头