달력

09

« 2010/09 »

  •  
  •  
  •  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  •  
  •  
Js로 Style 을 Control 하는 경우가 많이 있습니다.
자연스럽게 색깔 설정에도 손의 많이 가고, 그러다 보면 컬러코드를 가지고 작업을 해야 할 때가 있습니다.
이 팁은 이런 상황에서 유용하게 사용 됩니다.

IE6, IE7, Opera 같은경우 컬러코드 그대로 반환을 해 줍니다.
예를들어,
<div id="Some" style="background-color:#ffff00">someElement</div>

<script type="text/javascript">
alert(document.getElementById("Some").style.backgroundColor);
</script>
일 경우 #ffff00을 반환합니다.

하지만 FireFox, Safari 는
rgb(255, 255, 0) 을 반환합니다.

이렇게 되면 브라우져 별로 색상정의가 틀려져서, 여기서는 되고 저기서는 에러나고 하는 상황이 연출이 됩니다.

이럴경우 rgb코드를 16진수 컬러코드로 바꿔주는 함수입니다.

var getRgbToHex = function(rgb_code){
    if(Reg.test(rgb_code)){
        tempColor = rgb_code.replace(Reg, "");
        tempLength = tempColor.length - 1;
        tempColor = tempColor.substr(0, tempLength);
        tempColor = tempColor.split(",");

        red = tempColor[0];
        green = tempColor[1];
        blue = tempColor[2];

        colorCode = "#" + rgb_hex(red) + rgb_hex(green) + rgb_hex(blue);

        return colorCode;
    }
    return rgb_code;
}

var rgb_hex = function(color)
{
    if(color==0){
        var color="00";
        return color;
    }
    else{
        var y=color/16;
        var y=y+"a";
        if (y.indexOf(".")==-1){
            var hex2="0";
            var u=y.indexOf("a");
            var q=y.substring(0,u);
            var hex1=hex_array[q];
        }
        else{
            var l=y.split(".");
            var q=l[0];
            var z=q*16;
            var xyz=color-z;
            var hex1=hex_array[q];
            var hex2=hex_array[xyz];
        }
        var color=hex1+hex2;
        return color;
    }
}

Converter 하는 부분은 http://www.csgnetwork.com/csgcolorsel6.html를 참고했습니다.
사용법은

<script type="text/javascript">
var getColorCode = function(ele){
    nowColor = document.getElementById(ele).style.color;
    colorCode = getRgbToHex(nowColor);
    alert(colorCode);
</script>

<div id="some" style="color:#FF0000">Element</div>
<input type="button" value="getElementColorCode" onclick="getColorCode('some')">


크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Johan Kim 기다림