简体   繁体   English

使用angularjs更改背景和字体颜色

[英]Change background and font color with angularjs

Ok. 好。 So here is a noob question. 所以这是一个菜鸟问题。 I just started fooling around with angularjs and I was wondering if there is some sort of toggle function similar to ng-click or I have to build my own. 我刚开始玩angularjs,我想知道是否有某种类似于ng-click的切换功能,或者我必须自己构建。 What I want is to change the background and the font color of the body of my page, when the user checks the dark theme option. 我想要的是当用户检查黑暗主题选项时,更改我的页面正文的背景和字体颜色。
I managed to change the color on the click function but I need it to come back to initial state when it is not checked. 我设法改变了点击功能的颜色,但我需要它在没有检查时回到初始状态。 Any suggestions are welcome:) 欢迎任何建议:)

 <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body ng-app="myApp" ng-style="myStyle"> <label><input type="checkbox" ng-click="myStyle={background:'black', color:'white'}">Dark theme</label> <script> app = angular.module('myApp', []); </script> </body> </html> 

You can use ng-class to apply new classes to elements. 您可以使用ng-class将新类应用于元素。 The docs are here: https://docs.angularjs.org/api/ng/directive/ngClass 文档在这里: https//docs.angularjs.org/api/ng/directive/ngClass

I've done something similar in an app of my own, where selecting a theme from the options page applies a new class to the main content section of each page. 我在自己的应用程序中做了类似的事情,从选项页面中选择一个主题将新类应用到每个页面的主要内容部分。 I don't have the code available right now but I can post it in later if you would like. 我现在没有可用的代码,但如果您愿意,我可以在以后发布。

You'll want to add the style to the components .scss file or app.scss 您需要将样式添加到组件.scss文件或app.scss

.darkTheme {background:'black', color:'white'}

And then you could apply your style using the ng-class directive as Steve mentioned 然后你可以使用像Steve提到的ng-class指令来应用你的风格

<body ng-app="myApp" ng-class="{'darkTheme' : darkToggle}">

And add a model to the input 并在输入中添加模型

<input type="checkbox" ng-model="darkToggle">

Working solution 工作方案

 <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <style> .dark-theme { color: white; background: black; } </style> <body ng-app="myApp" ng-class="{'dark-theme': dark}"> <label><input type="checkbox" ng-model="dark">Dark theme</label> <script> app = angular.module('myApp', []); </script> </body> </html> 

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

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