如何在一个div中添加悬停背景图像风格Angularjs方式 [英] How to add a hover background image style on a div the Angularjs way

查看:259
本文介绍了如何在一个div中添加悬停背景图像风格Angularjs方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想有悬停切换一个div的背景图像。因为我使用的是绑定属性填写的信息,我不能改变这个类。据我所知,我没有看到任何方式与样式添加的HTML内悬停和我找到了一种方法做jQuery的,但它只是似乎并不像角的方式。

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.

推荐答案

方法1 :不控制,一切都在模板

Method #1: No controller, everything in template.

<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 :使用瓦尔存储值(使用一个控制器)

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>

控制器:

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 :保存最好的了!使用指令!

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 = '';
            })
        }
    };
});

控制器:

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.

演示: http://jsfiddle.net/TheSharpieOne/kJgVw/1/

这篇关于如何在一个div中添加悬停背景图像风格Angularjs方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆