Angular 2中带有供应商前缀的动态CSS样式 [英] Dynamic CSS Styles with Vendor Prefixes in Angular 2
问题描述
colorOne
和 colorTwo
.组件应该做的是用这两种颜色的渐变填充< div>
.如果我只是想为 div
提供 colorOne
的背景色,那不是问题,我可以使用< div [style.background] ="colorOne" class ="my-box"></div>
.但是,如果我想给它一个背景 gradient ,我就不知道如何做得很好,因为 background-gradient
需要使用供应商前缀.我能想到的唯一解决方案是检入javascript使用的浏览器.像这样:
public get headerColor(){//...确定浏览器let backgroundStyle =`linear-gradient(left top,$ {this.colorOne},$ {this.colorTwo})`;;如果(isWebkit){backgroundStyle ="-webkit-" + backgroundStyle;}否则,如果(isO){backgroundStyle ="-o-" + backgroundStyle;}否则,如果(isMoz){backgroundStyle ="-moz-" + backgroundStyle;}返回backgroundStyle;};
,然后使用< div [style.background] ="headerColor" class ="my-box"></div>
.有比这更好的解决方案吗?
您可以返回一个包含所有各种前缀值的字符串.仅使用相关的一个:
< div [style] ="stylish" class ="my-box"></div>
从'@ angular/platform-browser'导入{DomSanitizer};...构造函数(专用消毒剂:DomSanitizer,...){...}变得时尚(){let basicStyle =`linear-gradient(left top,$ {this.colorOne},$ {this.colorTwo})`;返回this.sanitizer.bypassSecurityTrustStyle(`背景:-o-$ {basicStyle};背景:-moz-$ {basicStyle};背景:-webkit-$ {basicStyle};`);}
Let's say I want to write a component in Angular 2 that has two input arguments: colorOne
and colorTwo
. What the component should do is to fill a <div>
with the gradient of those two colors.
If I just wanted to give the div
a background color of colorOne
it wouldn't be a problem, I could just use <div [style.background]="colorOne" class="my-box"></div>
. However, if I want to give it a background gradient, I wouldn't know how to do it nicely, because background-gradient
needs to be vendor prefixed. The only solution I could think of was checking in javascript which browser is used. Something like:
public get headerColor () {
//... determine the browser
let backgroundStyle = `linear-gradient(left top, ${this.colorOne}, ${this.colorTwo})`;
if (isWebkit) {
backgroundStyle = "-webkit-" + backgroundStyle;
} else if (isO) {
backgroundStyle = "-o-" + backgroundStyle;
} else if (isMoz) {
backgroundStyle = "-moz-" + backgroundStyle;
}
return backgroundStyle;
};
and then use <div [style.background]="headerColor" class="my-box"></div>
. Is there a better solution than this?
You could return a single string that contains all of the various prefixed values; only the relevant one will be used:
<div [style]="stylish" class="my-box"></div>
import { DomSanitizer } from '@angular/platform-browser';
...
constructor(private sanitizer: DomSanitizer, ...) { ... }
get stylish() {
let basicStyle = `linear-gradient(left top, ${this.colorOne}, ${this.colorTwo})`;
return this.sanitizer.bypassSecurityTrustStyle(`
background: -o-${basicStyle};
background: -moz-${basicStyle};
background: -webkit-${basicStyle};
`);
}
这篇关于Angular 2中带有供应商前缀的动态CSS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!