使用JS更改CSS RGBA背景颜色的alpha值

时间:2018-01-31 02:31:44

标签: javascript html css colors rgba

我的CSS中有这个:

.body {
    width: 150px;
    height: 40px;
    padding: 20px;
    background-color: rgba(255,0,0,1);
    text-align: center;
    border: 1px solid black;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    display: block;
    top: 50px;
    font-weight: bold;
    font-size: 25px;
}

我希望在用户点击按钮时更改background-color的不透明度(alpha):

<button onclick="lessColour()">-Colour</button>

如何创建此lessColour()功能,以便每次用户点击按钮时,background-color alpha会减少0.1

顺便说一句,我必须用3种不同的元素来做到这一点。

4 个答案:

答案 0 :(得分:2)

您需要创建一个带有两个参数的函数:

  • 要更改background-color不透明度的元素(或多个元素),以便您可以同时在多个元素中执行此操作。

  • 您想要更改的金额alpha(如果是正数则增加,如果是负数则减少)。

为了获得当前的alpha值,您需要:

  1. 使用getComputedStylegetPropertyValue获取当前background-color值。

  2. 解析该值以获得alpha组件。

  3. 使用background-color更新元素的element.style.backgroundColor

  4. 总之,它看起来像这样:

    // First, get all your elements:
    
    const a = document.getElementById('a');
    const b = document.getElementById('b');
    const c = document.getElementById('c');
    
    
    // And the buttons to update them:
    
    const decreaseA = document.getElementById('decrease-a');
    const decreaseAB = document.getElementById('decrease-ab');
    const decreaseABC = document.getElementById('decrease-abc');
    
    const increaseA = document.getElementById('increase-a');
    const increaseAB = document.getElementById('increase-ab');
    const increaseABC = document.getElementById('increase-abc');
    
    const decreaseAll = document.getElementById('decrease-all');
    const increaseAll = document.getElementById('increase-all');
    
    
    // Define your function:
    
    function updateColor(elements, change) {
    
      // Make sure elements is always an Array, so that you can call the
      // function with either an Array of elements or a single one (without
      // having to wrap it in an Array yourself.
      
      elements = Array.isArray(elements) ? elements : [elements];
     
      // Process all elements:
     
      elements.forEach(element => {
        // Get the current background-color value:
        const value = getComputedStyle(element).getPropertyValue("background-color");
        
        // Get all color components (alpha may not be there if = 1):
        const parts = value.match(/[\d.]+/g);
        
        // If alpha is not there, add it:
        if (parts.length === 3) {
          parts.push(1);
        }
        
        // Modify alpha:
        parts[3] = Math.min(1, Math.max(0, parseFloat(parts[3]) + change));
        
        // Set the element's text to be the current alpha value (just for the example):
        element.innerText = parts[3].toFixed(2);
        
        // Apply new value:
        element.style.backgroundColor = `rgba(${ parts.join(',') })`;
      });
    }
    
    
    // Add event handlers for the buttons that will call the function with the right params:
    
    decreaseA.onclick = () => updateColor(a, -0.1);
    decreaseAB.onclick = () => updateColor(b, -0.1);
    decreaseABC.onclick = () => updateColor(c, -0.1);
    
    increaseA.onclick = () => updateColor(a, 0.1);
    increaseAB.onclick = () => updateColor(b, 0.1);
    increaseABC.onclick = () => updateColor(c, 0.1);
    
    decreaseAll.onclick = () => updateColor([a, b, c] , -0.1);
    increaseAll.onclick = () => updateColor([a, b, c], 0.1);
    
    
    // Set the initial text inside each sample without modifying the color (just for the example):
    
    updateColor([a, b, c] , 0);
    body {
      margin: 0;
      font-family: monospace;
    }
    
    .samples {
      overflow: hidden;
    }
    
    .buttons {
      overflow: hidden;
      border: 2px solid #FFF;
    }
    
    span {
      float: left;
      width: 33.33333333%;
      line-height: 100px;
      height: 100px;
      text-align: center;
    }
    
    button {
      float: left;
      width: 33.33333333%;
      background: #000;
      color: #FFF;
      border: none;
      line-height: 32px;
      font-family: monospace;
      outline: none;
      border: 2px solid #FFF;
    }
    
    #decrease-all,
    #increase-all {
      width: 50%;
    }
    
    #a { background: rgba(255, 0, 0, 1); }
    #b { background: rgba(0, 255, 0, 1); }
    #c { background: rgba(0, 0, 255, 1); }
    <div class="samples">
      <span id="a"></span>
      <span id="b"></span>
      <span id="c"></span>
    </div>
    
    <div class="buttons">
      <button id="increase-a">INCREASE A</button>
      <button id="increase-ab">INCREASE B</button>
      <button id="increase-abc">INCREASE C</button>
      <button id="decrease-a">REDUCE A</button>
      <button id="decrease-ab">REDUCE B</button>
      <button id="decrease-abc">REDUCE C</button>
      <button id="increase-all">INCREASE ALL</button>
      <button id="decrease-all">REDUCE ALL</button>
    </div>

答案 1 :(得分:0)

希望有所帮助

function lessColour() {
  var elements = document.getElementsByClassName("opacityChange");
  var element, colors;
  for (i = 0; i < elements.length; i++) {
    element = getComputedStyle(elements[i]).getPropertyValue('background-color');
    //Get values
    colors = element.split(', ');
    colors[0] = parseFloat(colors[0].split('(')[1]);
    colors[1] = parseFloat(colors[1]);
    colors[2] = parseFloat(colors[2]);
    //Correct missing alpha
    if (colors.length == 3)
      colors[3] = 1;
    //Apply new style
    colors[3] = parseFloat(colors[3]) - 0.1;
    colors = 'rgba(' + colors.join(',') + ')';
    elements[i].style.backgroundColor = colors;
  }

}
.body {
  width: 150px;
  height: 40px;
  padding: 20px;
  background-color: rgba(255, 0, 0, 1);
  text-align: center;
  border: 1px solid black;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  display: block;
  top: 50px;
  font-weight: bold;
  font-size: 25px;
}

.circle {
  /*float: left;*/
  margin: 0 auto;
  height: 35px;
  width: 35px;
  border: 1px solid black;
  border-radius: 100px;
  background: rgba(0, 0, 0, 1);
  display: inline-block;
  margin-left: 10px;
}

.top {
  margin-left: 72px;
  height: 35px;
  width: 50px;
  border: 1px solid black;
  border-bottom-width: 2px;
  border-top-left-radius: 110px;
  border-top-right-radius: 110px;
  background: rgba(0, 0, 255, 1);
  display: block;
}
<div class="main">
  <div class="top opacityChange"></div>
  <div class="body opacityChange"></div>
  <div class="circle opacityChange"></div>
  <button onclick="lessColour()">-Colour</button>
</div>

答案 2 :(得分:0)

您可以封装一个使用getComputedStyle来猜测alpha的函数。

const setAlpha = (element, a) => {
   const current_color = getComputedStyle(element).getPropertyValue("background-color");
   const match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color);
   const a = a > 1 ? (a / 100) : a;
   element.style.backgroundColor = "rgba(" + [match[1],match[2],match[3],a].join(',') +")";
}

setAlpha(document.getElementById('elementName'), 0.1);

如果您想知道之前的alpha(可用于减少/增加的值):

const getBgAlpha = (element) => {
       const current_color = getComputedStyle(element).getPropertyValue("background-color");
       const match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color);
       return match[4];
}

答案 3 :(得分:-1)

function lessColour(){
   document.getElementById("butn1").style.backgroundColor = "rgba(0,0,0,0.1)";
}