我正在以角度6编写网站。我有两个组件,slideshow
和product-list
。
在我的幻灯片组件中,我有一个setTimeout。
public carousel() {
var i;
var y = document.getElementsByClassName("mySlides");
for (i = 0; i < y.length; i++) {
y[i].setAttribute("style", "none");
}
this.curIndex++;
if (this.curIndex > y.length) {this.curIndex = 1}
y[this.curIndex-1].setAttribute("style", "display:block;");
this.timer = setTimeout(() => {
this.carousel();
}, 4000);
}
它会改变幻灯片中的图像。如您所见,它每4秒发生一次。
到目前为止,这是预期的行为。
在我的产品列表组件中,我有一个随机颜色生成器。
getBackground (bg) {
const color = this.color(0.5);
return this._sanitizer.bypassSecurityTrustStyle(`
background: -moz-linear-gradient(top, ${color} 0%, ${color} 100%), url(${bg}) repeat 0 0;
background: -moz-linear-gradient(top, ${color} 0%, ${color} 100%), url(${bg}) repeat 0 0;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,${color}), color-stop(100%,${color})), url(${bg}) repeat 0 0;
background: -webkit-linear-gradient(top, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;
background: -o-linear-gradient(top, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;
background: -ms-linear-gradient(top, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;
background: linear-gradient(to bottom, ${color} 0%,${color} 100%), url(${bg}) repeat 0 0;
`);
}
这将返回带有随机颜色渐变的样式。
在我的产品列表组件
中调用它 <div class="rows" style="text-align: center">
<div *ngFor="let product of products; let i = index">
<div class="col-md-4 col-xs-6 clear product-list-item" title="{{product.product_name}}" routerLink="/product/{{product.product_id}}" [style]="getBackground('https://financialtribune.com/sites/default/files/field/image/17january/04-zs-ice-cream_66-ab.jpg')">
<div class="product-list-item-title">
<h1>{{product.product_name}}</h1>
</div>
<br>
<img class="product-list-item-image" src={{product.product_image_url}}>
<div class="product-list-item-description">
<h3>{{product.product_description}}</h3>
</div>
<div class="clear visible-lg" *ngIf="(i + 1) % 6 == 0"></div>
<div class="clear visible-md" *ngIf="(i + 1) % 4 == 0"></div>
<div class="clear visible-sm" *ngIf="(i + 1) % 3 == 0"></div>
<div class="clear visible-xs" *ngIf="(i + 1) % 2 == 0"></div>
</div>
</div>
</div>
但问题是,每次幻灯片改变时,我的颜色也会改变。
我怎样才能做到这一点,它不会改变任何东西?当幻灯片显示更改为新图片时,颜色会完全改变,因此我认为这是因为设置超时。
答案 0 :(得分:2)
在编写时,每次元素发生更改时都应调用getBackground()。但是如果你将样式赋值给属性值并在ngOnInit()中启动它就不会改变。创建一个包含产品颜色的数组:
<div *ngFor="let product of products; let i = index">
...
<div class="col-md-4 ...[style]="bg[i]">
...
打字稿:
bg = [];
ngOnInit(){
this.products.map(item => this.bg.push(this.getBackground('https://financialtribune.com/sites/default/files/field/image/17january/04-zs-ice-cream_66-ab.jpg'))
}
}