【发布时间】:2019-10-30 08:53:09
【问题描述】:
我有一个使用一种颜色的具有多个类的模板,我可以使用 javascript 将该颜色动态更改为另一种颜色吗?
页面加载后,找到所有的div、span、p、h,颜色为#512a69,改成#ef7e8e。
有可能吗?
谢谢。
【问题讨论】:
-
查看 CSS 变量,以及如何使用 JavaScript 操作它们的值。
标签: css colors prestashop
我有一个使用一种颜色的具有多个类的模板,我可以使用 javascript 将该颜色动态更改为另一种颜色吗?
页面加载后,找到所有的div、span、p、h,颜色为#512a69,改成#ef7e8e。
有可能吗?
谢谢。
【问题讨论】:
标签: css colors prestashop
这是一个解决方案,我将逐步解释。
首先,致电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 转换为十六进制以进行比较。这使用了内部的rgb2hex() 函数。
我希望这就是你要找的。p>
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");
【讨论】: