In Javascript how can I set rgba without specifying the rgb?

前端 未结 5 1102
旧巷少年郎
旧巷少年郎 2020-12-17 08:09

I have an HTML element whose background colour is set with rgba()

T

相关标签:
5条回答
  • 2020-12-17 08:43

    I had do this too but ended up writing something a little more specific. I put it in a jQuery plugin that accepts a min and max opacity:

    $.fn.setAlpha = function ( options ) {
        var settings = $.extend({
            alpha: 0.5,
            min: 0,
            max: 1
        }, options );
        return this.each(function() {
            var color = $(this).css('background-color');
            if (color.substring(0,4) === 'rgba') {
                var a;
                if (settings.alpha <= settings.min) {
                    a = settings.min;
                } else if (settings.alpha >= settings.max) {
                    a = settings.max;
                } else {
                    a = settings.alpha;
                }
                var rgba = color.replace(/[^,]+(?=\))/, a);
                $(this).css('background-color', rgba);
            }
        });
    }
    
    $.fn.getAlpha = function () {
    
        var color = this.css('background-color');
        if (color.substring(0,4) === 'rgba') {
            var alpha = color.split(',');
                alpha = alpha[alpha.length - 1].trim();
                alpha = alpha.substring(0, alpha.indexOf(")"));
            return alpha;
        } else {
            return 1;
        }
    }
    

    then you use them to do something like this to set a div to transparent and fade it to its original opacity as you scroll down:

    //get original opacity
    var originalOpacity = $('#myDiv').getAlpha(); 
    
    //set new opacity
    //it will be 0 at the top of the page
    var newOpacity = $(window).scrollTop()/500;
    $('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity}); 
    
    //on scroll fade new opacity to originalOpacity at 500px down
    $(window).scroll( function() {
         var newOpacity = $(window).scrollTop()/500;
         $('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
    }
    
    0 讨论(0)
  • 2020-12-17 08:46

    Does this help?

    http://www.phpied.com/rgb-color-parser-in-javascript/

    This may help in addition.

    Convert RGBA color to RGB

    0 讨论(0)
  • 2020-12-17 08:51

    After some playing around, and the discovery of getComputedStyle, I have put together this.

    <!DOCTYPE HTML>
    <html>
      <head>
        <style type="text/css">
          #element {
            background-color: rgb(10,10,10);
            background-color: rgba(10,10,10,1);
          }
        </style>
        <script type="text/javascript">      
          HTMLElement.prototype.alpha = function(a) {
            current_color = getComputedStyle(this).getPropertyValue("background-color");
            match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color)
            a = a > 1 ? (a / 100) : a;
            this.style.backgroundColor = "rgba(" + [match[1],match[2],match[3],a].join(',') +")";
          }
        </script>
      </head>
      <body>
        <div id="element">
          This is some content.
        </div>
        <script type="text/javascript">
          e = document.getElementById('element');
          e.alpha(20);
        </script>
      </body>
    </html>
    
    • Make sure you define in your css your values, and cascade because RGBA is CSS3.
    • Also see that you can pass in a number >1 for alpha and it will divide by 100 for you (I hate working with decimals when thinking percentages).
    • Enjoy!
    0 讨论(0)
  • 2020-12-17 08:51

    You could also use elem.style.opacity=0.5 or in html style="opacity:0.5". It is important to note that the child nodes will fade too.

    0 讨论(0)
  • 2020-12-17 08:52

    You got the string, replace whatever
    'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')

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