[英]How to get value of ON/OFF switch
我的網絡項目中有開/關切換器:
HTML:
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox"
id="myonoffswitch" checked>
<label class="onoffswitch-label" for="myonoffswitch">
<span #onoffswitch class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
CSS:
.onoffswitch-inner:before {
content: "ON";
padding-left: 10px;
background-color: #93297E; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}
我想知道切換器是打開還是關閉,我嘗試使用下一個代碼獲取該值,但它不起作用:
getSwitcherValue(onoffswitch) {
console.log("onoffswitch:"+onoffswitch.style.content);
}
您對如何獲得開/關切換器的價值有任何想法嗎?
使用onoffswitch.checked
代替onoffswitch.style.content
改成:
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox"
id="myonoffswitch" [(ngModel)]="isChecked">
<label class="onoffswitch-label" for="myonoffswitch">
<span #onoffswitch class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
並將isChecked
作為布爾值添加到ts文件中。
您正在使用Angular。 因此,請使用NgModel 。
<div class="onoffswitch">
<input type="checkbox" [(ngModel)]="onOff" name="onoffswitch" class="onoffswitch-checkbox"
id="myonoffswitch" checked>
<label class="onoffswitch-label" for="myonoffswitch">
<span #onoffswitch class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
在您的TS文件中:
public onOff = false;
現在,您只需檢查this.onOff
即可查看您的開關是否“打開”。
您可以嘗試此解決方案
HTML文件(例如app.component.html)
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox"
id="myonoffswitch" [checked]="isSwitched"
(change)="getSwitcherValue(isSwitched)">
<label class="onoffswitch-label" for="myonoffswitch">
<span #onoffswitch class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
Ts文件(app.component.ts)
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
isSwitched:boolean=true;
getSwitcherValue(onoffswitch) {
this.isSwitched=!this.isSwitched;
console.log("onoffswitch:"+this.isSwitched);
}
}
CSS文件(app.component.css)
.onoffswitch-inner:before {
content: "ON";
padding-left: 10px;
background-color: #93297E; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}
這是演示鏈接供參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.