![](/img/trans.png)
[英]How to add a diffrent background image to different div elements on hover?
[英]How to add a hover background image style on a div the Angularjs way
我在 div 上有一個背景圖像,我想在懸停時打開它。 我無法更改課程,因為我正在使用綁定屬性來填寫信息。 據我所知,我沒有看到任何方法可以在 html 內添加帶有樣式的懸停,我找到了一種在 jquery 中做到這一點的方法,但它看起來不像是有角度的方式。
方法#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>
方法#2 :使用變量存儲值(使用控制器)
<div ng-mouseenter="bg = imageOn"
ng-mouseleave="bg = imageOff"
style="background-image: url({{bg1}});">
</div>
控制器:
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.
}
方法#3 :把最好的留到最后! 使用指令!!
<div hover-bg-image="{{image}}"></div>
指令(如果有的話,可以改進以恢復到原始圖像......它的基本展示示例):
.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 = '';
})
}
};
});
控制器:
function withDirective($scope){
$scope.image = "http://www.gravatar.com/avatar/b76f6e92d9fc0690e6886f7b9d4f32da?s=100";
}
注意:控制器中的項目可以/應該/將動態設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.