简体   繁体   English

如何在angular6中的onclick上更改按钮的CSS?

[英]How to change the css of the button on onclick in angular6?

I have few buttons in my webpage. 我的网页上没有几个按钮。 I need to change the backgroundcolor & font-color when it is clicked. 单击时,我需要更改backgroundcolor和font-color。 I have tried this, 我已经试过了

<div class="card-body">
<h6 class="card-text">Data</h6>
<button ion-button block (click)="viewMore('data');
   displayPopup('data');" >
   ViewMore</button>&nbsp;
   <button ion-button block (click)="display('data');" >Display</button>
 </div> 

Likewise I have few more divs. 同样,我还有几个div。 Now I need to change the css of the viewmore button when it is clicked. 现在,我需要在单击它时更改viewmore按钮的css。

My css: 我的CSS:

button:focus{
 background-color: blue;
}
button:active{
background-color: red;
} 

Now it is working for second button, when I click the first button popup comes & after closing the popup button css has not changed. 现在它适用于第二个按钮,当我单击第一个按钮时,弹出窗口&关闭弹出按钮后的css尚未更改。 Can somebody please suggest me? 有人可以建议我吗?

The easiest way would be to use CSS pseudoclasses like you did. 最简单的方法是像您一样使用CSS伪类。 For clicked - or visited - elements, there's the :visited pseudoclass. 对于单击或访问的元素,有:visited伪类。

You should be familiar with basic css. 您应该熟悉基本的CSS。 W3schools is an awesome resource. W3schools是一个很棒的资源。

So in your case: 因此,在您的情况下:

button:visited {
   background: red;
}

:focus is - as the same says - for the element which has focus. :focus就像上面所说的那样-表示具有焦点的元素。

Or: 要么:

button:active,
button:visited,
button:focus {
   background: red;
}

Your question it's not clear. 您的问题尚不清楚。 The way to use ngStyle or ngClass otr style.attrib is used a variable and ternary operator. 使用ngStyle或ngClass otr style.attrib的方式是使用变量和三元运算符。 As you has severals buttons you need several variables. 由于有多个按钮,因此需要多个变量。 this variables can be a property of an object or an array. 此变量可以是对象或数组的属性。 As an array 作为数组

//You have an array
buttonsClicked:boolean[];
//In your .html

   <!--use index 0 for the first button, index 1 for the second button... -->
    <button ionbutton block [style.background-color]="buttonsClicked[0]?'red':'green'"
            (click)="buttonsClicked[0]=true;
                    viewMore('data');displayPopup('data');" >
       ViewMore</button>&nbsp;
       ....
     </div>

//when you close the popup you can clear all the buttonsClicked
this.buttonsClicked=[] //<--reinit the array

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

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