admin管理员组文章数量:1318156
I have a background image on a div that I want to have switch on hover. 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.
I have a background image on a div that I want to have switch on hover. 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.
Share Improve this question edited Nov 16, 2020 at 17:08 TheSharpieOne 25.7k9 gold badges70 silver badges80 bronze badges asked Feb 8, 2014 at 1:08 aintnorestaintnorest 1,4062 gold badges14 silver badges20 bronze badges 1- 3 Could you provide the code u are having now, so we can see your wrong output? – MiKE Commented Feb 8, 2014 at 1:22
1 Answer
Reset to default 8Method #1: No controller, everything in template.
<div ng-init="bg = ''"
ng-mouseenter="bg = 'http://www.gravatar./avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100'"
ng-mouseleave="bg = ''"
style="background-image: url({{bg}});">
</div>
Method #2: Using vars to store the values (uses a controller)
<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./avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
$scope.imageOff = ""; // image that would after after the mouse off.
}
Method #3: Saved the best for last! 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./avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
}
Note: The items in the controllers could/should/would be set dynamically.
Demos: http://jsfiddle/TheSharpieOne/kJgVw/1/
本文标签: javascriptHow to add a hover background image style on a div the Angularjs wayStack Overflow
版权声明:本文标题:javascript - How to add a hover background image style on a div the Angularjs way - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742041287a2417558.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论