使用jQuery或原生JS获取event-button类按钮背景色的RGB值
因为所有.event-button类按钮背景色完全一致,直接提取第一个按钮的渲染后背景色即可,无需遍历所有元素。
原生JavaScript实现
// 获取第一个.event-button元素 const targetBtn = document.querySelector('.event-button'); // 读取元素计算生效后的背景色,返回格式为rgb(r,g,b)或rgba(r,g,b,a) const renderedBgColor = window.getComputedStyle(targetBtn).backgroundColor; // 提取数值并截取前三位得到r、g、b const [r, g, b] = renderedBgColor.match(/\d+/g).slice(0, 3).map(Number); // 直接使用r、g、b三个数值即可 console.log('r值:', r, 'g值:', g, 'b值:', b);
jQuery实现
// 读取第一个.event-button的背景色 const renderedBgColor = $('.event-button').first().css('backgroundColor'); // 提取数值并截取前三位得到r、g、b const [r, g, b] = renderedBgColor.match(/\d+/g).slice(0, 3).map(Number); // 直接使用r、g、b三个数值即可 console.log('r值:', r, 'g值:', g, 'b值:', b);
补充说明
如果你的按钮背景色设置了透明度(返回rgba格式),上述代码中的slice(0,3)会自动过滤掉透明度数值,仅返回你需要的r、g、b三个基础色值。
内容的提问来源于stack exchange,提问作者Kirk Ross
相关产品推荐
相关产品推荐

