在 rgba 问题中替换 alpha

Replacing alpha inside rgba issue

我执行了以下函数来替换 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>

我做错了什么?

您的问题是认为样式会直接从函数更新。您只是在生成新样式,而不是更新背景颜色本身。这是您的代码的更新版本:

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

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);