javascript 在 AngularJS 中单击时更改 div 背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22747020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:42:34  来源:igfitidea点击:

Changing div background color on click in AngularJS

javascripthtmlcssangularjs

提问by krammer

I am using AngularJS to create tabs in my web page. How can I change the background color of the tab when it is clicked (selected) ?

我正在使用 AngularJS 在我的网页中创建选项卡。单击(选择)选项卡时,如何更改选项卡的背景颜色?

A JSFiddle for this code can be found at: http://jsfiddle.net/x8xfM/2/So for example, on clicking tab1, it becomes red in color, and when tab2 is clicked, tab1 goes black again and tab2 background color becomes red.

可以在以下位置找到此代码的 JSFiddle:http: //jsfiddle.net/x8xfM/2/例如,单击 tab1 时,它变为红色,单击 tab2 时,tab1 再次变为黑色,tab2 背景颜色变成红色。

<div  ng-app ng-controller="sample" ng-init="tab=1">

        <div class="cb" ng-click="tab = 1">tab 1</div>
        <div class="cb" ng-click="tab = 2">tab 2</div>

        <div ng-show="tab == 1">
            <p>first</p>
         </div>

        <div ng-show="tab == 2">
            <p>second</p>
        </div>
</div>

.cb {    
    list-style: none;
    padding: 10px;
    display:inline-block;
    background-color: #000;  
    color: #FFF;
    border: 1px solid black;
    border-radius: 5px;
}
.cb:hover{
    background-color: #4a4a4a; 
    color: #FFF;
}

回答by Seiyria

For the benefit of someone who might stumble across this from google:

为了那些可能从谷歌偶然发现这个的人的利益:

Use the ng-classdirective. Here's a jsfiddle using the above example: http://jsfiddle.net/x8xfM/43/

使用ng-class指令。这是使用上述示例的 jsfiddle:http: //jsfiddle.net/x8xfM/43/