我试图通过调用将组件属性设置为目标样式的组件中的函数来动态设置img元素的样式。但它没有用。
<div class="col-lg-2">
<a (click)="setColor('Black')">
<img class="img-fluid {{blackImgClass}}"
src="../assets/images/4ade25d4-3c31-45bd-a1e3-063b9f46c3d1_35.jpg">
</a>
</div>
<div class="col-lg-2 color-selection">
<a (click)="setColor('Stainless Steel')">
<img class="img-fluid {{stainlessImgClass}}"
src="../assets/images/62167c88-bf89-4848-acd6-c74d1970312a_35.jpg">
</a>
</div>
<div class="col-lg-2 color-selection">
<a (click)="setColor('White')">
<img class="img-fluid color-white {{whiteImgClass}}"
src="../assets/images/c79cd82b-37ea-43c4-b3ea-daceb08c4267_35.jpg">
</a>
</div>
该类在此函数的组件中设置:
private setColor(color: string) {
if (color == 'Black') {
this.productImages = this.product.images.black;
this.currentImage = this.product.images.black[0];
}
else if (color == 'White') {
this.productImages = this.product.images.white;
this.currentImage = this.product.images.white[0];
}
else if (color == 'Stainless Steel') {
this.productImages = this.product.images.stainless;
this.currentImage = this.product.images.stainless[0];
}
this.setCSSClass(color);
}
setCSSClass():
private setCSSClass(color) {
if (color == 'Black') {
this.whiteImgClass = '';
this.blackImgClass = 'border-bottom: 3px solid #f96302';
this.stainlessImgClass = '';
this.selectionColor = color;
}
else if (color == 'White') {
this.whiteImgClass = 'border-bottom: 3px solid #f96302';
this.blackImgClass = '';
this.stainlessImgClass = '';
this.selectionColor = color;
}
else if (color == 'Stainless Steel') {
this.whiteImgClass = '';
this.blackImgClass = '';
this.stainlessImgClass = 'border-bottom: 3px solid #f96302';
this.selectionColor = color;
}
}
答案 0 :(得分:0)
您正在设置class
两次,其中一个将被忽略。我也不确定带插值的绑定类是否有效。
我首先简化了css,因为所有三种图像样式共享一些基本属性 - 然后只需使用[ngStyle]
来设置颜色和您需要的任何其他css属性。
HTML
<img class="img-fluid basic-image-class" src="../assets/images/c79cd82b-37ea-43c4-b3ea-daceb08c4267_35.jpg"
[ngStyle]="currentImageStyles">
CSS
.basic-image-class: {border-bottom: 3px solid;}
代码
public currentImageStyles: string = '';
private setCSSClass(color) {
if (color == 'Black') {
this.currentImageStyles = {'border-bottom-color: #f96302'};
}
else if (color == 'White') {
this.currentImageStyles = {'border-bottom-color: #999'};
}
else if (color == 'Stainless Steel') {
this.currentImageStyles = {'border-bottom-color: #ccc'};
}
答案 1 :(得分:0)
你可以尝试这样 - 我动态地将最高值设置为我的绝对元素,并且我使用[style.top.px] =“top”进行设置,top是我的打字稿中的变量,在我计算后得到一个数字它的价值。只需设置你想要的东西
答案 2 :(得分:0)
如果我理解你,你需要将你的html更新为:
<img class="img-fluid color-white"
src="../assets/images/c79cd82b-37ea-43c4-b3ea-daceb08c4267_35.jpg"
class="color-white" [class.white-class]="yourCondition">
在哪里&#34; yourCondition&#34;当你想要添加&#34; white-class&#34;时应该返回true当你没有做错时。
在你的css中:
image.white-class{
//DO your stuff
}
对于多个类绑定,您可以使用如下所述的ngClass: