最近在学习ionic时一直遇到要动态控制元素样式的情况,在实践后总结了三种比较方便的方法
(一)通过 document.getElementById(id) 来动态控制元素样式
getElementById() 方法可返回对拥有指定 ID 的第一个对象的引用。因此,在操作一个特定的元素时,我们可以通过id来动态控制元素样式。具体代码如下:
//在ts文件中,我们可以通过boxShadow来控制id为'setcard'元素的阴影
document.getElementById('setcard').style.boxShadow="0px 0px 6px 3px #5ac5f4";
阴影属性说明(顺序依次对应):阴影的X轴(可以使用负值) 阴影的Y轴(可以使用负值) 阴影模糊距离 阴影的尺寸 阴影的颜色
(二)通过ngstyle来动态控制元素样式
[ngStyle]指令为元素添加 style 属性,具体代码如下:
//通过定义的isCheck来控制元素是否显示
<div style="height: 40px; background: #222222" [ngStyle]="{'display': isCheck===true ? 'block' : 'none'}"></div>
(三)通过ngclass来动态控制元素样式
ngclass中,第一个参数为类名称,第二个参数为boolean值,如果为true就添加第一个参数的类,具体代码如下:
//若ischeck为true,则为div添加addclass类
<div [ngClass]="{'addclass': ischeck}"></div>
其实相比于通过 document.getElementById(id) 来动态地控制样式,我更喜欢用ngStyle来控制样式,主要是因为我有一次用document.getElementById(id)来控制底栏是否display的时候点击跳转再返回,再想要显示底栏的时候显示不出来了,而当时我换成用ngStyle控制底栏的display却没有这个问题。
还原一下当时差不多的bug情况:
//首页按钮代码html
<button ion-item block color="danger" border class="btn-login" (click)="show()">开始测试</button>
<button ion-item block id="isshow" color="danger" border class="btn-login" (click)="gotest()">test</button>
//首页按钮样式 css
.btn-login {
text-align: center;
color: white;
// height: 40px;
font-size: 18px;
}
#isshow{
display: none;
}
//首页ts文件
check=true;
show(){
console.log('点击开始测试');
console.log('更改前',document.getElementById('isshow').style.display);
if(this.check) {
document.getElementById('isshow').style.display='block';
}
else{
document.getElementById('isshow').style.display='none';
}
this.check=!this.check;
console.log('点击完成');
console.log('更改后',document.getElementById('isshow').style.display);
}
//跳转页面ts文件
go(){
console.log('跳转回来');
this.navCtrl.push('LoginPage');
}
如果有大佬知道原因,一定要留言指导!!!
资料参考链接:
ngclass以及ngstyle:https://blog.youkuaiyun.com/u013589443/article/details/72866603