不用等UI改图, 实现icon(非svg或者ttf图标)或者GIF图片跟随主题色
- 例如将logo换成红色
- 代码
/**
*
* @param {*} color_1 你想变成什么颜色
* @param {*} color_2 目前是什么颜色 #ff0000
* @param {*} include 要改变颜色的dom, 默认body
* @param {*} external 排除掉的dom, 可不传
* @returns
*/
function hueDifference(color_1, color_2 = '#ff0000', include = 'body', external = []){
const format = (c) => { return c.length === 7 ? c.slice(1) : c} // 去掉#号
const h2d = (h) => { return parseInt(h, 16); } // convert a hex value to decimal
const d2Angle = (r, g, b) => { // 角度
const angle = (Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b) / Math.PI) * 180;
return angle > 0 ? angle : 360 + angle;
}
color_1 = format(color_1);
const r1 = h2d(color_1.substr(0,2));
const g1 = h2d(color_1.substr(2,2));
const b1 = h2d(color_1.substr(4,2));
const angle1 = d2Angle(r1, g1, b1);
color_2 = format(color_2);
const r2 = h2d(color_2.substr(0,2));
const g2 = h2d(color_2.substr(2,2));
const b2 = h2d(color_2.substr(4,2));
const angle2 = d2Angle(r2, g2, b2);
let angle = angle1 - angle2;
if (r1 == g1 && g1 == b1) {
angle = 0;
}
([].concat(include)).map(selector => {
const el = document.querySelector(selector);
console.log(el, `hue-rotate(${angle}deg)`);
if (!el) return
el.style.setProperty('filter', `hue-rotate(${angle}deg)`);
});
([].concat(external)).map(selector => {
const el = document.querySelector(selector);
if (!el) return
el.style.setProperty('filter', `hue-rotate(${-angle}deg)`);
});
}
/* 调用 */
hueDifference('#ff494f', '#2a87ff', 'body', ['article', '.avatar'])
- 把上面的代码复制到浏览器的控制台试试看