通过JavaScript在所有css样式中更改一种颜色

toe95027  于 2023-06-25  发布在  Java
关注(0)|答案(1)|浏览(110)

我有一个使用一种颜色的多个类的模板,我可以使用JavaScript动态地将该颜色更改为另一种颜色吗?
加载页面时,找到所有div、span、p、h,颜色#512a69,并将其更改为#ef7e8e。
这可能吗?
谢谢

ffx8fchx

ffx8fchx1#

这里有一个解决方案,我将逐步解释。
首先,调用colorReplace("#512a69", "#ef7e8e");。第一个值是目标颜色,第二个值是替换颜色。
在其中,$('*').map(function(i, el) {将选择DOM树中的所有标签。对于每个元素,返回其getComputedStyle(el)样式数组。您可以自定义选择器以加快处理速度(例如$('div').map(function(i, el)) {)。
所有包含“颜色”的样式属性(例如background-color-moz-outline-color等),将检查颜色值是否等于目标颜色。如果是这样,它将被替换为目标颜色。
返回的颜色是rgba(0,0,0,0)rgb(0,0,0),而不是#FFFFFF,所以快速转换从rgb到hex进行比较。它使用内部rgb2hex()函数。
我希望这是你正在寻找的。

function colorReplace(findHexColor, replaceWith) {
    // Convert rgb color strings to hex
    // REF: https://stackoverflow.com/a/3627747/1938889
    function rgb2hex(rgb) {
        if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

    // Select and run a map function on every tag
    $('*').map(function(i, el) {
        // Get the computed styles of each tag
        var styles = window.getComputedStyle(el);

        // Go through each computed style and search for "color"
        Object.keys(styles).reduce(function(acc, k) {
            var name = styles[k];
            var value = styles.getPropertyValue(name);
            if (value !== null && name.indexOf("color") >= 0) {
                // Convert the rgb color to hex and compare with the target color
                if (value.indexOf("rgb(") >= 0 && rgb2hex(value) === findHexColor) {
                    // Replace the color on this found color attribute
                    $(el).css(name, replaceWith);
                }
            }
        });
    });
}

// Call like this for each color attribute you want to replace
colorReplace("#512a69", "#ef7e8e");

来源:https://stackoverflow.com/a/30724171/1136132

相关问题