使用 ng-repeat 在 AngularJS 鼠标悬停时激活 .gif

Activate .gif on mouseover in AngularJS with ng-repeat

我已经看到很多使用 jQuery 回答这个问题的答案。像这样: Stop a gif animation onload, on mouseover start the activation and Animating a gif on hover。 但我正在寻找一种方法来使用 angular。我认为它应该与 jQuery 中的做法相同。我想做的正是第一个 link 中提出问题的人想要做的,但在 angular 中:

  1. 页面加载时 => 所有 gif 动画都已停止

  2. 鼠标悬停时 => 为那个 gif 启动动画

  3. 在鼠标移开时 => 该 gif 的动画再次停止

这是我 HTML 中的内容:

<img class="projectGif" src="{{project.gifUrl}}" ng-mouseover="animation(project)">

我传递给动画函数的 "project" 对象是我在我的代码中从 ng-repeat="project in projects" 获取的对象。然后在我的 JavaScript 中:

$scope.animation = function(project) {
    //not sure what to do here
};

我在 angular 文档页面上四处寻找类似于 jQuery $(this).attr() 的东西,发现了 $attr 和 $set 之类的东西,我想也许我可以只需使用它们将我的 img 标签中的 src 设置为我的 img 的路径。所以就像 $set('src', 'project.imgUrl') 但我在我的控制台中收到一个错误 $set is not defined

所以我的主要问题是,如何使用 angular 使我的网页以静态 .gif(或 img 等)开头,然后在悬停时更改静态 .gif到动画 .gif?

使用 Animating a gif on hover, create a directive 中的技术,为静态 gif 和动画 gif 提供 url,然后使其在鼠标悬停时在两个图像之间切换。

您也可以使用 Extending Angular Directive

中描述的技术

创建指令后,您的 html 可能看起来像

<img ng-src="{{project.staticUrl}}" custom-src-on-mouseover="{{project.gifUrl}}">

纯HTML

<img  ng-repeat="project in vm.projects"
      ng-src="{{project.gifUrl}}"
      ng-init="project.gifUrl=project.staticUrl"
      ng-mouseover="project.gifUrl=project.dynamicUrl"
      ng-mouseleave="project.gifUrl=project.staticUrl">

或混合解决方案:

HTML

<div ng-controller="myController as vm">
    <img ng-repeat="project in vm.projects"
         ng-src="{{project.gifUrl}}"
         ng-init="project.gifUrl=project.staticUrl"
         ng-mouseover="vm.setDynamic($index)"
         ng-mouseleave="vm.setStatic($index)">
</div>

JS

var vm = this;
vm.setDynamic = function(index) { 
    vm.projects[index].gifUrl = vm.projects[index].dynamicUrl; 
};
vm.setStatic  = function(index) { 
    vm.projects[index].gifUrl = vm.projects[index].staticUrl; 
};

请注意,我正在使用 ng-repeat 指令的 $index 特殊 属性。有关 ng-repeat$index 的更多信息,请参阅 AngularJS ngRepeat API Docs