我正在用angular 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秒发生一次。
到目前为止,这是预期的行为。
在我的product-list组件中,我有一个随机颜色生成器。
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;
`);
}
这将返回具有随机颜色渐变的样式。
在这里,它在我的product-list组件中被调用
<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>
但问题是,每次幻灯片改变时,我的颜色也会改变。
我怎样才能让它不会改变任何东西呢?当幻灯片变成新的图片时,颜色就会发生变化,所以我认为这是因为settimeout。
发布于 2018-06-14 18:05:40
在编写时,每次元素发生变化时都应该调用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'))
}
}
https://stackoverflow.com/questions/50841494
复制相似问题