jQuery set CSS background opacity

前端 未结 4 1707
终归单人心
终归单人心 2020-12-06 06:14

I have a

whose transparency of its background-color (and not its contents) I\'d like to change. A remote API sends me this colour:

相关标签:
4条回答
  • 2020-12-06 06:52

    You may try this

    function convertHex(hex,opacity){
        hex = hex.replace('#','');
        r = parseInt(hex.substring(0,2), 16);
        g = parseInt(hex.substring(2,4), 16);
        b = parseInt(hex.substring(4,6), 16);
        result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
        return result;
    }
    
    $('h1').css('background', convertHex('#A7D136', 0.5));
    

    An example here.

    0 讨论(0)
  • 2020-12-06 06:59

    try parseInt(hex,16) to convert hex string into decimal int

    so in this case it'll be:

    var color = '#abcdef';
    var rgbaCol = 'rgba(' + parseInt(color.slice(-6,-4),16)
        + ',' + parseInt(color.slice(-4,-2),16)
        + ',' + parseInt(color.slice(-2),16)
        +',0.5)';
    $('div').css('background-color', rgbaCol)
    

    you should create a function out of this to use in your application.

    0 讨论(0)
  • You may use this javascript helper function

    function setColorOpacity(colorStr, opacity) {
      if(colorStr.indexOf("rgb(") == 0)
      {
        var rgbaCol = colorStr.replace("rgb(", "rgba(");
        rgbaCol = rgbaCol.replace(")", ", "+opacity+")");
        return rgbaCol;
      }
    
      if(colorStr.indexOf("rgba(") == 0)
      {
        var rgbaCol = colorStr.substr(0, colorStr.lastIndexOf(",")+1) + opacity + ")";
        return rgbaCol;
      }
    
      if(colorStr.length == 6)
        colorStr = "#" + colorStr;
    
      if(colorStr.indexOf("#") == 0)
      {
        var rgbaCol = 'rgba(' + parseInt(colorStr.slice(-6, -4), 16)
            + ',' + parseInt(colorStr.slice(-4, -2), 16)
            + ',' + parseInt(colorStr.slice(-2), 16)
            + ','+opacity+')';
        return rgbaCol;
      }
      return colorStr;
    }
    
    0 讨论(0)
  • 2020-12-06 07:03

    This should work for you. It does assume that you are passing a valid 6 digit hex code and an opacity, and does no error checking.

    function hex2rgba(hex, opacity)
    {
        //extract the two hexadecimal digits for each color
        var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
        var matches = patt.exec(hex);
    
        //convert them to decimal
        var r = parseInt(matches[1], 16);
        var g = parseInt(matches[2], 16);
        var b = parseInt(matches[3], 16);
    
        //create rgba string
        var rgba = "rgba(" + r + "," + g + "," + b + "," + opacity + ")";
    
        //return rgba colour
        return rgba;
    }
    
    $(".box").css("background-color", hex2rgba("#ABCDEF", 0.6));
    

    You can view an example of this on jsFiddle here

    0 讨论(0)
提交回复
热议问题