Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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進数)を表示しています

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした