我正在尝试使用[ngStyle]设置悬停属性状态。以下仅设置正常的状态颜色。当我将鼠标悬停在按钮上时,该按钮不会按预期更改为按下的颜色。
<button (click)="logout()"
class="btn register-button"
[ngStyle]=" hover ? {'color': theme.logoutButtonColorPressed,
'border-color': theme.logoutButtonBorderColorPressed,
'background-color': theme.logoutButtonBackgroundColorPressed } :
{'color': theme.logoutButtonColorNormal,
'border-color': theme.logoutButtonBorderColorNormal,
'background-color': theme.logoutButtonBackgroundColorNormal }">Logout</button>
答案 0 :(得分:10)
如果要在悬停时切换样式,请将以下内容添加到按钮
<button (mouseover)="hover=true" (mouseleave)="hover=false"...
答案 1 :(得分:3)
如果您需要通过更改ngstyle来选择单个按钮,这就是我所做的。
<强> btn.component.html 强>
<div *ngIf="socketData && socketData.status === 'ok'">
<div *ngFor="let button of socketData.message; let i = index"
[ngStyle]="hovered === i ? pressedStyle(button) : buttonStyle(button)"
(mouseover)="hovered = i"
(mouseout)="hovered = -1"
(click)="reqTicket(button.id)">
{{button.someImportantData}} - {{button.yetMoreImportantData}}
</div>
</div>
<强> btn.component.ts 强>
export class ButtonComponent implements OnInit {
style;
hovered;
...
private buttonStyle(button) {
let btnType = this.setBtnType(button);
this.style = {
'color': '#' + button.textColor,
'font-size': button.textSize + 'px',
'background-color': btnType.background
};
return this.style;
}
private pressedStyle(button) {
let pressed = this.setBtnType(button, this.hovered);
this.style['background-color'] = pressed.background;
return this.style;
}
private setBtnType(button, hovered?) {
let type = 'normal';
let btn = {
normal: {
background: '#' + button.backColor,
},
pressed: {
background: '#' + button.backColor,
}
}
if(hovered > -1) type = 'pressed';
return {
border: btn[type].width + ' ' + btn[type].color + ' ' + 'solid',
background: btn[type].background
};
}
}
希望这有助于某人:)
答案 2 :(得分:1)
:hover
是伪类,无法使用style
添加。您应该使用CSS和ngClass
或[class.xxxx]=".."
。