【问题标题】:Changing linear gradient on color picker change在颜色选择器更改时更改线性渐变
【发布时间】:2020-10-13 19:32:06
【问题描述】:

我在由以下 html 和 typescript 代码设置的图像上有一个默认的线性渐变:

<header [style.background-image]="cv2HeaderStyle('0, 0, 0, 0.1', '0, 0, 0, 0.8')"></header>

cv2HeaderStyle(rgba1: string, rgba2: string) {
    return this.sanitizer.bypassSecurityTrustStyle(
      `linear-gradient(to bottom, rgba(${rgba1}), rgba(${rgba2})),
        url(${'../../../assets/imgs/woman-girl-silhouette-jogger-40751.jpg'})`
    );
  }

在一个表单中,我有一个 ngx-color-picker 的下拉菜单,允许用户更改线性渐变的 rgba 值。

 <input 
              (colorPickerChange)="updateFirestoreColor($event)" 
              id="filmColorPicker" 
              [(colorPicker)]="color" 
              [style.background]="color"
              [cpOutputFormat]='auto'/>

我正在使用函数将我的 typescript 文件中的十六进制代码转换为 rgba 值,然后尝试使用新的 rgba 值设置新的 cv2HeaderStyle,但是,以下代码不起作用:

updateFirestoreColor(color) {
    var setColor1WithOpacity = this.hexToRgb(color) + ', 0.1)';
    var setColor2WithOpacity = this.hexToRgb(color) + ', 0.8)';
    this.cv2HeaderStyle(setColor1WithOpacity, setColor2WithOpacity);
  }

hexToRgb(hex){
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',');
    }
    throw new Error('Bad Hex');
  }

我没有任何控制台日志错误,并且控制台正在获取正确的 rgba 值

【问题讨论】:

  • this.hexToRgbA 里面是什么? this.cv2HeaderStyle 向这个方法发送相同颜色的 rgba1 和 rgba2 参数
  • 我更新了帖子

标签: javascript css angular


【解决方案1】:

您需要在 .html 中包含“参数”-或使用变量-

<header [style.background-image]="cv2HeaderStyle(color1, color2)">
//or
<header [style.background-image]="myBackground">

在更新FirestoreColor

updateFirestoreColor(color) {
    this.color1=setColor1WithOpacity = this.hexToRgb(color) + ', 0.1)';
    this.color2=setColor2WithOpacity = this.hexToRgb(color) + ', 0.8)';
     //or 
    const setColor1WithOpacity = this.hexToRgb(color) + ', 0.1)';
    const setColor2WithOpacity = this.hexToRgb(color) + ', 0.8)';
    myBackground=this.cv2HeaderStyle(setColor1WithOpacity, setColor2WithOpacity);
  }

注意:不要使用“var”来声明临时变量,如果您希望更改变量的值,请使用“let”,如果该值在函数内部不再更改,请使用 const

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多