简体   繁体   English

按钮不会更改背景和文本的颜色

[英]buttons not changing colour of background and text

I'm apparently doing something wrong with this code. 我显然对此代码做错了。 Not sure what but its going really wrong. 不知道是什么,但它确实出错了。

I'm wanting it so that when you click a button the colour the background and the text changes font, Currently not happening 我想要它,以便当您单击按钮的颜色时背景和文本会更改字体,目前没有

<style>
.red { background-color: red; }
.red p { font-style: normal; }

.blue { background-color: blue; }
.blue p { font-style: italic; }

.green { background-color: green; }
.green p { font-style: oblique;}
</style>
<div ng-class={{colorScheme}}>

    <button ng-click="colorScheme = 'red'">ColorScheme Red</button>
    <button ng-click="colorScheme = 'blue'">ColorScheme Blue</button>
    <button ng-click="colorScheme = 'green'">ColorScheme Green</button>

    <p>Awesome content</p>

</div>

Just pass the scope variable to ng-class like 只需将范围变量传递给ng-class

 var app = angular.module('my-app', [], function() {}) app.controller('AppController', function($scope) {}) 
 .red { background-color: red; } .red p { font-style: normal; } .blue { background-color: blue; } .blue p { font-style: italic; } .green { background-color: green; } .green p { font-style: oblique; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="my-app" ng-controller="AppController"> <div ng-class="colorScheme"> <button ng-click="colorScheme = 'red'">ColorScheme Red</button> <button ng-click="colorScheme = 'blue'">ColorScheme Blue</button> <button ng-click="colorScheme = 'green'">ColorScheme Green</button> <p>Awesome content</p> </div> </div> 

If you use ng-class don't put expressions{{}} just use directly the scope object. 如果您使用ng-class,则不要放置表达式{{}},而直接使用范围对象。 Because its default directive in angular they didn't expect the expressions {{}} 因为它的默认指令为angular,所以他们不希望表达式{{}}

Otherwise Use class with expression in the way of I am answered 否则以回答我的方式使用带有表达式的类

<div class="{{colorScheme}}">

    <button ng-click="colorScheme = 'red'">ColorScheme Red</button>
    <button ng-click="colorScheme = 'blue'">ColorScheme Blue</button>
    <button ng-click="colorScheme = 'green'">ColorScheme Green</button>

    <p>Awesome content</p>

</div>

Since you also tagged JQuery... this works for me: 由于您还标记了JQuery ...这对我有用:

$("button").click(function(){
    $(this).parent().removeClass().addClass($(this).attr('color'));
});

Here is the JSFiddle demo :) 这是JSFiddle演示 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM