【问题标题】:Change CSS RGBA background color's alpha value using JS使用 JS 更改 CSS RGBA 背景颜色的 alpha 值
【发布时间】:2018-07-10 01:19:49
【问题描述】:

我的 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-coloralpha 会减少0.1

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

【问题讨论】:

  • 您的意思是您需要从 3 个不同的按钮更改 body 的不透明度还是更改 3 个不同元素的不透明度?
  • 所以,我有 1 个具有 3 个不同元素的 div。身体、顶部和圆圈。我需要编写一个脚本,当我单击此按钮时,这些元素(对象)的背景不透明度将以 0-1 的比例减少 0.1。
  • 你必须检测元素的当前颜色还是它总是会是红色
  • 所以...如果它从 255,0,0,1 开始,我按下按钮 1 次将变成 255,0,0,0.9,如果我再次按下 255,0, 0,0.8,但如果我按下另一个按钮,将再次转动 255,0,0,0.9。
  • 那么,您是否尝试过自己编写此代码。你似乎确切地知道需要发生什么。您为什么不研究一下如何使用 JavaScript 更改元素的背景颜色,尝试一下,然后提出问题。

标签: javascript html css colors rgba


【解决方案1】:

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

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

  • 您要更改的数量alpha(如果为正则增加或如果为负则减少)。

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

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

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

  3. 将元素的background-color 更新为element.style.backgroundColor

总而言之,它看起来像这样:

// 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>

【讨论】:

  • 还是不行,让我再试一次
  • 元素已经具有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; }
  • 如示例中所示。所有三个#a#b#c 元素已经在CSS 中使用background 属性定义了初始背景颜色。我没有看到问题。
  • 是的,我无法真正改变这个结构。
  • 我能想象到这可能不起作用的唯一情况是,如果您在样式表中使用!important 设置了一些background-color。在这种情况下,只需将这一行:element.style.backgroundColor = `rgba(${ parts.join(',') })`; 替换为另一行:element.style.backgroundColor = `rgba(${ parts.join(',') }) !important`;
【解决方案2】:

希望对你有帮助

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>

【讨论】:

  • 元素已经具有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; }
  • .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; }
  • 如果初始background-coloralpha1getComputedStyle(element).getPropertyValue('background-color')将返回rgb(255, 0, 0)而不是rgba(255, 0, 0, 1),所以你的代码将无法工作,因为它会尝试将rgb(255,0,0),0.9) 分配为新的backgroundColor。您正在错误地解析当前值。
  • .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; }
  • 我无法真正改变这个结构。
【解决方案3】:

您可以封装一个使用 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];
}

【讨论】:

    【解决方案4】:
    function lessColour(){
       document.getElementById("butn1").style.backgroundColor = "rgba(0,0,0,0.1)";
    }
    

    【讨论】:

    • 给你的按钮一个id,我以“butn1”为例。
    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 2011-02-07
    • 1970-01-01
    • 2017-12-16
    • 2011-10-22
    • 2015-08-27
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多