【问题标题】:Cannot get background style using javascript无法使用 javascript 获取背景样式
【发布时间】:2020-10-22 21:35:23
【问题描述】:

我正在尝试获取test div 的简单十六进制代码值。我遵循与this 帖子完全相同的原则,尽管我不明白。应该登录到控制台的是十六进制代码#0ff0ff

var test = document.getElementById('test'),
    window.getComputedStyle(test);

console.log(style.getPropertyValue('background'));
#test {
  background: #0ff0ff;
}
<div id='test'>test</div>

任何想法我哪里出错了?感谢您的帮助

【问题讨论】:

  • 如果你 .getPropertyValue('background-color') 会发生什么?

标签: javascript


【解决方案1】:

将 RGB 从 theblackgigant's answer 添加到 HEX CODE。 RGB转十六进制代码Erick Petrucelli's Solution

var test = document.getElementById("test");

//Get the color Code
  var theCSSprop = window.getComputedStyle(test, null).getPropertyValue("background-color");
  
//Most browsers seem to return the RGB value
//Function to Convert RGB to Hex Code
function rgb2hex(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]);
}

//Output
console.log(rgb2hex(theCSSprop));
#test {
  background: #0ff0ff;
}
<div id='test'>test</div>

【讨论】:

    【解决方案2】:

    您没有将window.getComputedStyle(test) 的值存储在变量style 中。

    请注意,getPropertyValue('background-color') 返回的是 RGB 值而不是 HEX 代码。

    var test = document.getElementById('test');
    
    var style = window.getComputedStyle(test);
    
    console.log(style.getPropertyValue('background-color'));
    #test {
      background: #0ff0ff;
    }
    <div id='test'>test</div>

    【讨论】:

    • RGB 或非 RGB 完全取决于浏览器。 (现代人返回 RGB/A 但谁知道有一天可能会决定返回 HEX/A)@user875
    • 酷,不知道,我以为它总是RGB
    • 确实 :) 关于返回值和 getComputedStyle:stackoverflow.com/a/60689673/383904 - 如果 OP 在比较颜色之后...
    猜你喜欢
    • 1970-01-01
    • 2014-02-24
    • 2014-10-31
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多