[英]How to add a hover background image style on a div the Angularjs way
I have a background image on a div that I want to have switch on hover.我在 div 上有一个背景图像,我想在悬停时打开它。 I can't change the class because I'm using a bound property to fill in the information.
我无法更改课程,因为我正在使用绑定属性来填写信息。 As far as I know I don't see any way to add hover with styles inside of the html and I found a way to do it in jquery but it just doesn't seem like the angular way.
据我所知,我没有看到任何方法可以在 html 内添加带有样式的悬停,我找到了一种在 jquery 中做到这一点的方法,但它看起来不像是有角度的方式。
Method #1 : No controller, everything in template.方法#1 :没有控制器,一切都在模板中。
<div ng-init="bg = ''"
ng-mouseenter="bg = 'http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100'"
ng-mouseleave="bg = ''"
style="background-image: url({{bg}});">
</div>
Method #2 : Using vars to store the values (uses a controller)方法#2 :使用变量存储值(使用控制器)
<div ng-mouseenter="bg = imageOn"
ng-mouseleave="bg = imageOff"
style="background-image: url({{bg1}});">
</div>
Controller:控制器:
function myCtrl($scope){
$scope.bg1 = "" // this is the default image.
$scope.imageOn = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
$scope.imageOff = ""; // image that would after after the mouse off.
}
Method #3 : Saved the best for last!方法#3 :把最好的留到最后! Using a directive!!
使用指令!!
<div hover-bg-image="{{image}}"></div>
Directive (could be improved to revert back to original image if there is one... its basic to show example):指令(如果有的话,可以改进以恢复到原始图像......它的基本展示示例):
.directive('hoverBgImage',function(){
return {
link: function(scope, elm, attrs){
elm.bind('mouseenter',function(){
this.style.backgroundImage = 'url('+attrs.hoverBgImage+')';
});
elm.bind('mouseleave',function(){
this.style.backgroundImage = '';
})
}
};
});
Controller:控制器:
function withDirective($scope){
$scope.image = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
}
Note: The items in the controllers could/should/would be set dynamically.注意:控制器中的项目可以/应该/将动态设置。
Demos: http://jsfiddle.net/TheSharpieOne/kJgVw/1/演示: http : //jsfiddle.net/TheSharpieOne/kJgVw/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.