LoginSignup
13
12

More than 5 years have passed since last update.

JavaScriptでカーソル位置にある要素の背景色を取得する

Last updated at Posted at 2015-08-31

Gif.gif

Chromeだと色情報を取得ができましたがブラウザによってはできないかも?

html

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div id="colorCode"></div>

css

.box:nth-child(1){
  background: #f9f918;
}
.box:nth-child(2){
  background: rgba(0,0,255,0.7);
}
.box:nth-child(3){
  background: #55BEFC;
}
.box:nth-child(4){
  background: #55BE2E;
}
.box:nth-child(5){
  background: #993E7E;
}

※配置などの部分は省略しています。

javascript

var bgColor;
var colorCode = document.querySelector('#colorCode');

document.onmouseover = function (e) {
  // IE用
  if(!e){
    e = window.event;
    bgColor = e.target.currentStyle.backgroundColor;
  }else{
    // 色情報取得
    bgColor = window.getComputedStyle(e.target, '').backgroundColor;
  }

  // RGB(A)からHexへ変換
  var rgb = rgbToHex(bgColor);

  // 透明度を取得
  var alpha = /\d+\.\d+/.exec(bgColor);

  colorCode.textContent = bgColor.replace(/\d+\.\d+/, Number(alpha).toFixed(1))+', #'+rgb;  
}

// RGB(A)からHexへ変換
function rgbToHex (color) {
    var ret = /rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),?\s*([.\d]+)?\)/.exec(color);
    var rgbHex = '';
    for(var i=1;i<=3;i++){
      var hex = Number(ret[i]).toString(16);
      rgbHex += (hex.length === 1)? '0' + hex : hex; 
    }
    return rgbHex;
}

要素に透明度が指定してある場合はRGBAで表示されます
RGBA と Hex(16進数)を表示しています

13
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12