简体   繁体   中英

How to change CSS color of a button via NativeScript?

I just started using Nativescript . I have a button declared in the XML calling ( id="mainButton" class="btn" ) an external css file. Everything works fine (button originally renders in blue). However, I need to change its color to red, via code.

How to do that?

I've tried the line below without success (no errors in the console but the page does not render anymore):

page.css = "mainButton { backgroundColor: red }";

A simple solution would be to get an instance of the button using its id mainButton . Then changing the css or the View instance's backgroundColor property.

For example say you have this event on the tap event for the button:

function changeColor(args) {
   var btn = args.object;
   btn.backgroundColor = "#3489db";
}

In your xml:

<Button tap="changeColor" class="whatever" />

There are plenty of other approaches on when to execute but that should help you figure it out :)

You can do that directly in your css file like this

Button {
  background-color: red;
}

or

.button-class {
   background-color: red;
}

and you can also update the highlight-color too

Button:highlighting {
   background-color: green;
}

and you can use the style property in js/ts and dont forget to import Color from tns-core-modules/color

buttonInstance.style.backgroundColor = new Color("#00FF00");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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