在rgba内替换alpha问题

问题描述 投票:0回答:1

我做了以下函数来替换rgba字符串中的alpha。

function replaceAlpha(elemAttr,alpha) {
    elemAttr = elemAttr.replace(elemAttr.substring(elemAttr.lastIndexOf(",")+1,elemAttr.lastIndexOf(")")),alpha)
}

但它似乎并不奏效,即使结果是正确的,请看:

function replaceAlpha(elemAttr,alpha) {
    elemAttr = elemAttr.replace(elemAttr.substring(elemAttr.lastIndexOf(",")+1,elemAttr.lastIndexOf(")")),alpha)
    console.log(elemAttr)
}
replaceAlpha(document.getElementById("invisibleSpan").style.backgroundColor,0)
<span id="invisibleSpan" style="background-color: rgba(0,0,0,0.5);color:white">I wanna be invisible</span>

我到底做错了什么?

javascript css background-color alpha
1个回答
2
投票

你的问题是认为样式会直接从函数中更新。你只是简单地生成了新的样式,但没有更新背景颜色本身。这里是你的代码的更新版本。

我只是从你的函数中返回你的新值 并将其设置为新的背景色。

function replaceAlpha(elemAttr,alpha) {
    return elemAttr.replace(elemAttr.substring(elemAttr.lastIndexOf(",")+1,elemAttr.lastIndexOf(")")),alpha)
}

const elem = document.getElementById("invisibleSpan")
const rgba = replaceAlpha(elem.style.backgroundColor,0);
elem.style.backgroundColor = rgba;

如果你想从函数中更新它,你可以这样做。

function replaceAlpha(element,alpha) {
    const backgroundColor = element.style.backgroundColor;
    const [r,g,b,a] = backgroundColor.split(',');
    const newBackgroundColor = [r,g,b,alpha].join(',') + ')';

    element.style.backgroundColor = newBackgroundColor;
}

const elem = document.getElementById("invisibleSpan")
replaceAlpha(elem, 0);

增加了一个从函数本身更新任何元素和颜色属性的方法。注意,这并没有处理验证。如果你不检查你要替换的属性是否真的是一种颜色,你可能会遇到错误,我把这个任务留给你。

function replaceAlpha(element, attribute, alpha) {
    const color = element.style[attribute];
    const [r,g,b,a] = color.split(',');
    const newColor = [r,g,b,alpha].join(',') + ')';

    element.style[attribute] = newColor;
}

const elem = document.getElementById("invisibleSpan")
replaceAlpha(elem, 'backgroundColor',0);
© www.soinside.com 2019 - 2024. All rights reserved.