我的网络项目中有开/关切换器:
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);
}
您对如何获得开/关切换器的价值有任何想法吗?
答案 0 :(得分:0)
使用onoffswitch.checked
代替onoffswitch.style.content
答案 1 :(得分:0)
更改为:
<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文件中。
答案 2 :(得分:0)
您正在使用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
即可查看您的开关是否“打开”。
答案 3 :(得分:0)
答案 4 :(得分:0)
您可以尝试此解决方案
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;
}
这里是Demo链接以供参考