web standard/script2022. 8. 25. 09:39

잡설 : 한동안 실무를 놨더니 기본개념부터 가물가물하다. 나 스스로를 위해 기초부터 다시 되짚어보고자 한다..

 

var는 es6 이전 변수를 정의할때 사용하는 구문

자비로운 javascript 덕분에 var는 오류가 날것 같은 상황에서도 에러를 내뱉지 않음

 

예를 들어.. 첫번째 케이스를 보자.

console.log(a);
var a = 0;
console.log(a);

// 결과
undefined
0

해당 코드는 일반인이 봤을땐 코드 순서대로 실행할것 같다고 판단하겠지?? java나 C++에서도 그렇게 판단할것 같다.

근데 javascript는 최초 브라우져 엔진이 코드에 접근했을때 변수나 함수 선언된 놈들을 끄집어내 메모리에 저장한다.

최상단 전역으로 올리는 행위 즉 호이스팅 한다고 표현한다.

 

그렇다보니 console을 실행하기 전에 변수 a를 선언한걸 먼저 호이스팅 하기 때문에 undefined가 출력된다.

이루 a를 0으로 할당하고 두번째 console을 실행할때 0의 값이 출력되는것

 

또는 이런 경우도 있다... 두번째 케이스.

for (var i=0; i < 5; i++) {
    console.log(i)
}
console.log(i)

// 결과
0
1
2
3
4
5

저기서 변수 i는 지역변수다. 전역에서 접근되면 안되는..

근데 보는바와 같이 접근이 가능해서 5가 출력된다.

var로 선언된 지역변수는 function에서만 보장된다는 블라블라....

 

이걸 보완하고자 나온게 let

 

첫번째 케이스를 let으로 바꿔보자

console.log(a);
let a = 0;
console.log(a);

// 결과
Uncaught ReferenceError: a is not defined at <anonymous>

에러가 난다. a는 아직 정의되지 않았다고..

var와 마찬가지로로 호이스팅은 한다. 대신 접근할 수 없는 TDZ라는 곳에 임시저장된 뒤 선언할때 접근 가능한 저장소로 옮겨진다고 한다.

 

for (let j=0; j < 5; j++) {
    console.log(j)
}
console.log(j)

// 결과
0
1
2
3
4
Uncaught ReferenceError: j is not defined at <anonymous>

위와 마찬가지 에러가 난다.

 

이걸 통해 var와 let의 차이.. 그리고 호이스팅이 뭔지 개념에 대해 이해해보자.

Posted by 수라
web standard/script2015. 4. 24. 15:34

/* OS & 버젼 체크 */

function getOSVer() {
    var mobileOS;    // will either be iOS, Android or unknown
    var mobileOSver; // this is a string, use Number(mobileOSver) to convert
    var uaindex;
    // determine OS
    if ( agentString.match(/iPad/i) || agentString.match(/iPhone/i) ) {
        mobileOS = 'iOS';
        uaindex  = agentString.indexOf( 'OS ' );
    } else if ( agentString.match(/Android/i) ) {
        mobileOS = 'Android';
        uaindex  = agentString.indexOf( 'Android ' );
    } else {
        mobileOS = 'unknown';
    }
    // determine version
    if ( mobileOS === 'iOS'  &&  uaindex > -1 ) {
        mobileOSver = agentString.substr( uaindex + 3, 1 ).replace( '_', '.' );
    } else if ( mobileOS === 'Android'  &&  uaindex > -1 ) {
        mobileOSver = agentString.substr( uaindex + 8, 1 );
    } else {
        mobileOSver = 'unknown';
    }
    if (mobileOS === 'iOS') {
        $("body").addClass(mobileOS+mobileOSver);
    } else if (mobileOS === 'Android') {
        $("body").addClass(mobileOS+mobileOSver);
    }
}

Posted by 수라
web standard/script2011. 11. 21. 20:30

<script type="text/javascript">

frmUrl = 'http://www.naver.com/a.htm?ace=1214&enter=6001'  //예문용 경로입니다. 사용하실때는 아랫줄의 경로를 이용하세요
//frmUrl = location.href                 //사용하실대는 이줄의 주석을 지우고 상단의 예문을 지우세요


varCut = frmUrl.indexOf("?")               //전송된 값을 받기위해 ?의 순서를 찾습니다.

varCheck = frmUrl.substring(varCut+1)           //?의 뒷값을 구하여 사용할 값을 뽑아냅니다.

var varList = varCheck.split("&")              //&를 기준으로 배열변수로 만들어놓습니다.

forCount = varList.length                //총배열갯수를 구합니다.

for(i=0; i < forCount; i++)                 //배열갯수만큼 포문을 돌려 변수를 정의합니다.
 {
  eval(varList[i])                  //경로의 특성을 살려 eval로 그냥 쉽게 뽑아놨습니다.
  /*
  변수를 새로 지정하고 싶다면
 
  포문 위에 var 변수명 = new Array 을 쓰고

  도는 포문앞에 변수명[i] = varList[i]

  로 바까쓰시면 됩니다.
  */
 }

 


/*
해당 경로의 받아온값을 바로 변수화 해서 사용합니다.

request("ace")로 받아야할값은 ace의 변수로 저장이되고 값은 1214그대로 사용됩니다.

아래 처럼 변수가 지정되어 값을 가지고있습니다.
*/

alert(ace)     //테스트용 얼럿창
alert(enter)    //테스트용 얼럿창

</script>


Posted by 수라
web standard/script2011. 8. 10. 14:17
원본글 : http://blog.outsider.ne.kr/129

자바스크립트가 강력해 지면서 DOM을 다루는 스크립트를 많이 사용하곤 한다. Ajax를 하면 특히 많이 사용하기도 하고 그 외에 편리한 UI를 위해서 동적(Dynamic)으로 자바스크립트를 이용해서 HTML의 내용을 바꾸거나 구조를 변환하거나 한다. 여기서 동적이라는 의미는 HTML문서를 작성할때 HTML코드를 입력한 것이 아니라 HTML페이지의 랜더링 후에 페이지를 사용하면서 스크립트를 이용해서 순간순간 바꾼다는 뜻이다.

이런 부분이 자바스크립트가 재밌는 점이기도 하면서 잘 활용하면 여러가지 편리한 인터페이스나 효과를 제공할 수 있다.

하지만 이렇게 동적으로 바꾸었다고 하더라도 브라우저에서 제공하는 "소스보기"를 하면 처음 작성한 HTML코드만 나올뿐 동적으로 생성한 코드를 볼 수가 없다. 동적으로 생성한 HTML이 내가 의도한 대로 잘 안나오면 간단한 것은 스크립트 부분을 보면서 해결할 수 있지만 소스가 복잡하다면 스크립트코드만 보면서 생성되는 HTML코드를 예상하는 것은 생각처럼 만만치 않을 때가 있지만 실제로 생성된 HTML코드를 볼 수 있다면 디버깅하는데 훨씬 편리할 수 있다.(왠만한 HTML Syntax에러는 에디터에 붙혀만 넣어놔도 발견할 수 있으니까....)

이게 불가능 한 줄로만 알고 있었는데 동적으로 생성한 코드를 볼 수 있는 방법이 있다.

document.documentElement.innerHTML

위 코드를 실행하면 현재 눈에 보이는 랜더링상태의 HTML코드를 볼 수 있다.

간단하게는

alert(document.documentElement.innerHTML);

를 통해서 볼 수 있지만 이렇게 할 경우 일단 줄바꿈이 제대로 되지 않으며 alert창에서는 복사를 할 수도 없고 또 긴코드는 alert창으로 다 볼 수도 없다. alert창에는 스크롤이 없으므로....(테스트 중인게 아니라면 대개의 경우 alert에서 보여줄 수 있는 야을 넘어갈 것이다.

그래서 동적으로 생성되는 코드를 볼 수 있도록 간단한 예제를 만들어 보았다.

document.documentElement.innerHTML 예제보기


document.documentElement.innerHTML에서 나온값은(head~/body 까지 나온다.) html코드이기 때문에 일반적인 방법으로 페이지에 찍어내도 다시 렌더링 되어버려서 소스코드를 볼 수가 없다.(결국 이것도 동적으로 생성한 것이니까...) 소스를 볼 수 있는 <xmp></xmp>코드를 이용해서 HTML코드가 찍히도록 할 수도 있는데 보통의 HTML페이지 소스에서는 스크립트 코드가 당연히 들어가 있을 것이기 때문에 </script>부분에서 결국 깨져버린다.

위의 예제에서는 textarea를 이용했다. textarea에 찍으면 html코드도 그대로 찍히니까 가장 간단한 방법일 것이다. 복사해서 에디터쪽에 붙히기만 하면 되니까....  예제를 약간 설명(?)하면 div를 하나두고 그안에 있는 change버튼을 누르면 div안의 내용을 스크립트를 이용해서 바꾸어 주었고 소스보기 버튼을 누르면 현재상태의 html코드가 textarea에 찍히는데 change버튼을 누르기 전에 소스보기를 눌러보고 바꾼 후에 눌러보면 쉽게 달라진 점을 비교할 수 있을 것이다.

귀찮아서 그렇게 까지는 안했지만 일반적으로 게시판에디터에서 하듯이 document.documentElement.innerHTML에서 나온 값의 태그가 동작하지 않도록 &lt; &gt;등으로 바꾸어줘서 찍어주는 방법도 있을 것이다.

머 보여주는 방법보다는 일단 본수 있다는게 중요한거니까.. ㅎㅎㅎ


'web standard > script' 카테고리의 다른 글

OS & 버젼 체크  (0) 2015.04.24
url의 변수값을 스크립트로 가져오기  (0) 2011.11.21
오늘하루 창닫기 소스  (0) 2011.06.27
레이어팝업(오늘하루창닫기) 소스  (1) 2011.06.16
탭메뉴 스크립트  (0) 2011.01.06
Posted by 수라
web standard/script2011. 6. 27. 16:25
[index]
<script language="JavaScript">
<!--
function setCookie( name, value, expiredays ){
    var todayDate = new Date();
    todayDate.setDate( todayDate.getDate() + expiredays );
    document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}
function getCookie( name ){
    var nameOfCookie = name + "=";
    var x = 0;
    while ( x <= document.cookie.length ) {
        var y = (x+nameOfCookie.length);
        if ( document.cookie.substring( x, y ) == nameOfCookie ) {
            if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 ) endOfCookie = document.cookie.length;
            return unescape( document.cookie.substring( y, endOfCookie ) );
        }
        x = document.cookie.indexOf( " ", x ) + 1;
        if ( x == 0 ) break;
    }
    return "";
}
//첫번째 새창띄우기 시작
if ( getCookie( "cookie01" ) != "done" ){ //cookie01는 쿠키의 이름
    noticeWindow = window.open('popup01.html','popup01','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=300,top=0,left=0');// 팝업창의 경로, 이름, 그외 스크롤바와 크기,위치 설정부분
    noticeWindow.opener = self;
}
// -->
</script>



[popup]
<script language="JavaScript">
<!--

function setCookie( name, value, expiredays ) {
    var todayDate = new Date();
    todayDate.setDate( todayDate.getDate() + expiredays );
    todayDate.setHours(0);
    todayDate.setMinutes(0);
    todayDate.setSeconds(0);
    document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

function close_day() {
    //if ( document.forms[0].chkbox.checked ) //'오늘은이창을....'부분의 체크박스와 관련된 값입니다. chkbox는 chkbox의 name값
    setCookie( "cookie01", "done" , 1); // 쿠키값 체크
    self.close();
}

//3일동안열지않음
function close_3day() {
    setCookie( "cookie01", "done" , 3); // 쿠키값 체크
    self.close();
}

// 한달동안 열지 않음
function close_month() {
    setCookie( "cookie01", "done" , 30); // 쿠키값 체크
    self.close();
}

function close_window() {
    self.close();
}

// 새창띄우고 링크적용 후 팝업창닫기
function link_blank(url) {
    window.open(url);
    self.close();
}
// 부모페이지에 링크적용 후 팝업창닫기
function link_opener(url){
    opener.window.location.href=url;
    self.close();
}

// -->
</script>

[html1]
<ul>
    <li><a href="javascript:;" onclick="link_blank('http://test.com');">새창링크</a></li>
    <li><a href="javascript:;" onclick="link_opener('http://test.com');">부모창링크1</a></li>
</ul>
<a href="javascript:;" onclick="close_day();">하루동안 열지 않음</a>
<a href="javascript:;" onclick="close_3day();">3일동안 열지 않음</a>
<a href="javascript:;" onclick="close_month();">한달동안 열지 않음</a>
<a href="javascript:;" onclick="close_window();">닫기</a>

[html2]
<form name="popup">
    <ul>
        <li><a href="javascript:;" onclick="link_blank('http://test.com');">새창링크</a></li>
        <li><a href="javascript:;" onclick="link_opener('http://test.com');">부모창링크1</a></li>
    </ul>
    <input type="checkbox" name="chkbox" onclick="close_day()">오늘 하루 페이지를 열지 않습니다.
    <a href="javascript:;" onclick="close_window();">닫기</a>
</form>

[html3]
<form name="popup">
    <ul>
        <li><a href="javascript:;" onclick="link_blank('http://test.com');">새창링크</a></li>
        <li><a href="javascript:;" onclick="link_opener('http://test.com');">부모창링크1</a></li>
    </ul>
    <input type="checkbox" name="chkbox">오늘 하루 페이지를 열지 않습니다.
    <a href="javascript:;" onclick="close_window();">닫기</a>
</form>





Posted by 수라
web standard/script2011. 6. 16. 15:08
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=euc-kr" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>레이어팝업 데모</title>
    <style type="text/css">
        * {
            margin:0;
            padding:0;
        }
        body {
            font-family:Dotum,"돋움",Verdana,sans-serif;
            font-size:12px;
            line-height:14px;
        }
        div#wikiWrap {
            position:relative;
            width:760px;
            height:442px;
        }
        div#son {
            position:absolute;
            top:30px;
            right:150px;
            width:430px;
            height:311px;
            padding:10px 10px 30px;
            background:#FFF;
        }
        div#son div {
            overflow:hidden;
            width:100%;
            padding-top:3px;
        }
        div#son div p {
            float:left;
            margin-top:5px;
        }
        div#son div p input {
            width: 13px;
            height: 13px;
            vertical-align: middle;
        }
        div#son div button {float:right;}
    </style>
    <script type="text/javascript">
    //쿠키생성과 닫기기능
        function getCookie( name )
        {
            var nameOfCookie = name + "=";
            var x = 0;
            while ( x <= document.cookie.length )
            {
                var y = (x+nameOfCookie.length);
                if ( document.cookie.substring( x, y ) == nameOfCookie )
                {
                    if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
                        endOfCookie = document.cookie.length;
                    return unescape( document.cookie.substring( y, endOfCookie ) );
                }
                x = document.cookie.indexOf( " ", x ) + 1;
                if ( x == 0 )
                    break;
            }
            return "";
        }
        function DivTodayClose()
        {
            setCookie( "popCookie", "done" , 1 ); //popCookie : 쿠키의 네이밍은 임의 설정하면 됨.
            document.getElementById('son').style.display = "none"; //son : 레이어팝업 id 연결
        }
        function DivClose()
        {
            document.getElementById('son').style.display = "none";
        }
        function setCookie( name, value, expiredays )
        {
            var today = new Date();
            today.setDate( today.getDate() + expiredays );
            document.cookie = name + "=" + escape(value) + "; path=/; expires=" + today.toGMTString() + ";";
        }
    </script>
    <script type="text/javascript">
    //레이어팝업 드래그기능
        var dragapproved=false
        var minrestore=0
        var initialwidth,initialheight
        var ie5=document.all&&document.getElementById
        var ns6=document.getElementById&&!document.all
        function iecompattest(){
            return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
        }
        function drag_drop(e){
            if (ie5&&dragapproved&&event.button==1){
                document.getElementById("son").style.left=tempx+event.clientX-offsetx+"px"
                document.getElementById("son").style.top=tempy+event.clientY-offsety+"px"
            }
            else if (ns6&&dragapproved){
                document.getElementById("son").style.left=tempx+e.clientX-offsetx+"px"
                document.getElementById("son").style.top=tempy+e.clientY-offsety+"px"
            }
        }
        function initializedrag(e){
            offsetx=ie5? event.clientX : e.clientX
            offsety=ie5? event.clientY : e.clientY
            tempx=parseInt(document.getElementById("son").style.left)
            tempy=parseInt(document.getElementById("son").style.top)
 
            dragapproved=true
            document.getElementById("son").onmousemove=drag_drop
        }
        function stopdrag(){
            dragapproved=false;
            document.getElementById("son").onmousemove=null;
        }
    </script>
    </head>
    <body>
        <div id="wikiWrap">
            <img src="http://doctype.kr/wiki/lib/exe/fetch.php?media=%E3%84%B9:mother.jpg" alt="바닥페이지" />
            <div id="son" style="position:absolute; cursor:move; left:150px; top:30px;" onmousedown="initializedrag(event)" onmouseup="stopdrag()"><!-- 드래그 기능을 위해 펑션 연결 -->
                <img src="http://doctype.kr/wiki/lib/exe/fetch.php?media=%E3%84%B9:son.jpg" alt="" />
                <div>
                    <p>
                        <input type="checkbox" id="todayClose" onclick="DivTodayClose();" title="24시간동안 창을 열지 않습니다." />
                        <label for="todayClose">오늘 하루 이창을 열지 않습니다.</label>
                    </p>
                    <button type="button" title="닫기" onclick="DivClose();"><span>닫기</span></button>
                </div>
                <script type="text/javascript">
                //생성한쿠키 연결, 오늘 하루 창을 열지않기 기능을 위해 아래 소스가 필요.
                    cookiedata = document.cookie;
                    if ( cookiedata.indexOf("popCookie=done") < 0 ) //popCookie : 쿠키의 네이밍 연결.
                    {     
                        document.getElementById('son').style.display = "block"; //son : 레이어팝업 id 연결
                    }
                        else
                    {
                        document.getElementById('son').style.display = "none";
                    }
                </script>
            </div>
        </div>
    </body>
</html>
Posted by 수라
web standard/script2011. 1. 6. 17:23
<script type="text/javascript">
<!--
// tab
function initTabMenu(tabContainerID) {
var tabContainer = document.getElementById(tabContainerID);
var tabAnchor = tabContainer.getElementsByTagName("a");
var i = 0;

for(i=0; i<tabAnchor.length; i++) {
if (tabAnchor.item(i).className == "tab")
thismenu = tabAnchor.item(i);
else
continue;

thismenu.container = tabContainer;
thismenu.targetEl = document.getElementById(tabAnchor.item(i).href.split("#")[1]);
thismenu.targetEl.style.display = "none";
thismenu.imgEl = thismenu.getElementsByTagName("img").item(0);
thismenu.onclick = function tabMenuClick() {
currentmenu = this.container.current;
if (currentmenu == this)
return false;

if (currentmenu) {
currentmenu.targetEl.style.display = "none";
if (currentmenu.imgEl) {
currentmenu.imgEl.src = currentmenu.imgEl.src.replace("_on.gif", ".gif");
}
else {
currentmenu.className = currentmenu.className.replace(" on", "");
}
}
this.targetEl.style.display = "";
if (this.imgEl) {
this.imgEl.src = this.imgEl.src.replace(".gif", "_on.gif");
}
else {
this.className += " on";
}
this.container.current = this;

return false;
};

if (!thismenu.container.first)
thismenu.container.first = thismenu;
}
if (tabContainer.first)
tabContainer.first.onclick();
}
//-->
</script>

<table id="news_tab" border='1' bordercolor='#DFDFDF' style='border-collapse:collapse' cellpadding='5' cellspacing='0'>
<tr bgcolor='#F4F4F4'>
<td><a href="#news1" class="tab">tab menu1</a></td>
<td><a href="#news2" class="tab">tab menu2</a></td>
<td><a href="#news3" class="tab">tab menu3</a></td>
<td><a href="#news4" class="tab">tab menu4</a></td>
<td><a href="#news5" class="tab">tab menu5</a></td>
<td><a href="#news6" class="tab">tab menu6</a></td>
<td><a href="#news7" class="tab">tab menu7</a></td>
<td><a href="#news8" class="tab">tab menu8</a></td>
<td><a href="#news9" class="tab">tab menu9</a></td>
<td><a href="#news20" class="tab">tab menu20</a></td>
<td><a href="#news21" class="tab">tab menu21</a></td>
<td><a href="#news22" class="tab">tab menu22</a></td>
</tr>
<tr>
<td colspan='12'>
<table id="news1"><tr><td>tab menu1 contents1</td></tr></table>
<table id="news2"><tr><td>tab menu2 contents2</td></tr></table>
<table id="news3"><tr><td>tab menu3 contents3</td></tr></table>
<table id="news4"><tr><td>tab menu4 contents4</td></tr></table>
<table id="news5"><tr><td>tab menu5 contents5</td></tr></table>
<table id="news6"><tr><td>tab menu6 contents6</td></tr></table>
<table id="news7"><tr><td>tab menu7 contents7</td></tr></table>
<table id="news8"><tr><td>tab menu8 contents8</td></tr></table>
<table id="news9"><tr><td>tab menu9 contents9</td></tr></table>
<table id="news20"><tr><td>tab menu20 contents20</td></tr></table>
<table id="news21"><tr><td>tab menu21 contents21</td></tr></table>
<table id="news22"><tr><td>tab menu22 contents22</td></tr></table>
</td>
</tr>
</table>
<script type="text/javascript">
initTabMenu("news_tab");
</script>

Posted by 수라
web standard/script2011. 1. 6. 16:30
<style>
.redcolor{
 color:red;
}
.bluecolor{
 color:blue;
}
</style>

 

<div id="test" class="redcolor">테스트</div>
<div>마우스 오버시 색갈이 변합니다. <br><a href="#" onmouseover="colorchage('test','redcolor');">빨간색</a> <a href="#" onmouseover="colorchage('test','bluecolor');">파란색</a></div>

 

<script>
// 아이디, 클래스명
function colorchage(id,color){
 document.getElementById("test").className = color;
}
</script>

Posted by 수라
web standard/script2010. 11. 17. 09:23

<style type="text/css">
label.on{color:blue;font-weight:bold}
</style>
<script type="text/javascript">
function Set_Faq(obj){
 var Faq_dtList = document.getElementById("radioFom").getElementsByTagName("label");
 for (i=0;i<Faq_dtList.length;i++) {
  if(obj==Faq_dtList[i]){
  Faq_dtList[i].className = (Faq_dtList[i].className = "on" ? "on" : "")  
  } else {
  Faq_dtList[i].className = ""
  }
 }
}
</script>

 

<form id="radioFom" method="post" action="">
 <label for="aa" onclick="Set_Faq(this)" class="on"><input type="radio" id="aa" name="rdo" checked="check" />하하</label><br />
 <label for="bb" onclick="Set_Faq(this)"><input type="radio" id="bb" name="rdo" />하하</label><br />
 <label for="cc" onclick="Set_Faq(this)"><input type="radio" id="cc" name="rdo" />하하</label><br />
 <label for="dd" onclick="Set_Faq(this)"><input type="radio" id="dd" name="rdo" />하하</label><br />
</form>


Posted by 수라
web standard/script2010. 5. 13. 16:11
출처 : http://www.dillerdesign.com/experiment/DD_belatedPNG/
js파일 다운로드

<!--[if IE 6]>
<script src="/inc/js/DD_belatedPNG_0.0.8a-min.js"></script>
<script>
  /* EXAMPLE */
  DD_belatedPNG.fix('.png_bg');
 
  /* string argument can be any CSS selector */
  /* .png_bg example is unnecessary */
  /* change it to what suits you! */
</script>
<![endif]-->


[example]
<img src="" class="png_bg" alt="" />


이하원본================================================================================================

IE6만 쓰던 시절엔 png투명이미지를 아예 쓸 생각을 하지않았는데, IE6이하를 제외한 거의 모든 브라우저,

심지어 IE조차 7부터는 png24 투명/반투명이미지를 지원하기에 단지 IE6때문에 유용한 png파일 사용을 못하기엔 안타깝다는 생각이 많이 든다.

 

예전부터 크게 두가지 방법이 있긴 했다.

1. DXImageTransform.Microsoft.AlphaImageLoader어쩌고로 시작하는 방법

배경에는 속성(repeat,position)적용이 안됨, 물론 배경이 아닌 단순한 이미지를 삽입하거나 배경에 repeat과 같은 속성이 필요없을시에는 요긴하게 쓰일수도있다.


2. iepngfix.htc 이런식의 IE전용인 .htc파일을 불러들여 IE에서만 읽고 실행하는 방법.

이방법이 계속 발전해서 투명 png 배경이미지속성까지 제어가 가능한 이곳의 버전2를 사용하기위해서는

기 본적인 .htc파일과 css 배경 속성지원을 위한 .js파일 그리고 blank.gif 라는 작은 투명이미지등이 필요해 약간 귀찮아 보이긴 하지만, .img나 background에 관련된 css속성 지원, 투명png hover지원등 거의 완벽하게 IE6에서 png24투명이미지를 보통의 gif 나 jpg 파일처럼 쓸수있게되었다.

그 런데 문제는 투명이미지의 경우 바로 투명으로 뜨지않고, 일전의 형식(이미지의 투명한 부분이 회색바탕으로 나오는)으로 우선 보였다가 .js 화일을 읽어들이고 나서야 투명이 되기때문에 페이지를 열었을때 깜박이는 fliker 현상이 일어난다는 점.

그리 가볍지도 않은 .js,.htc 파일을 항상 로드해야된다는점 등이 아쉬운점이었다.

 


위의 두가지 방법외에 몇가지 새로운 소스들이 있어 소개해 본다.

   

 Unit PNG Fix

2kb바이트도 채 안되는 자바스크립트 한줄의 추가로 모든것이 해결되는 정말 좋은 소스라고 생각된다.

   1: <!--[if lt IE 7]>
   2:         <script type="text/javascript" src="unitpngfix.js"></script>
   3: <![endif]-->

IE filter로 인한 깜박이는 문제(fliker) 해결, 자동으로 페이지 내 모든 투명이미지에 적용, auto width, auto height, background repeat 속성지원등 괜찮은 소스이다.

그러나 간혹 jquery를 이용한 dropdown menu 나 slide toggle 등이 z-index를 이용해 png배경위에 놓였을때 펼쳐지지 않을 때가있음이 발견되었고, background-position은 지원이 되지않는다.

IE6만을 위한 코드이므로 IE5.5 이하의 버전에서는 어찌될지 모르겠다.

우선 원하는 페이지에 적용해보고 이상이 없다면, 현재로선 가장 간단한 방법이 아닌가 싶다.

 

 Achieve alpha transparency in IE6 without the need of an HTTP request

별도의 자바스크립트를 추가하기 원하지 않는 사람들을위해 예전에 사용하던 1번방식이 좀더 발전된 소스라고 보면 되겠다.

   1: * html * { behavior: expres\sion( (this.runtimeStyle.behavior = "none") 
   2: && 
   3: (this.currentStyle.backgroundImage.toString().toLowerCase().indexOf('.png')>-1) 
   4: && ( this.runtimeStyle.filter = 
   5: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + 
   6: this.currentStyle.backgroundImage.toString().replace('url("','').replace('")','') 
   7: + "', sizingMethod='crop')", this.runtimeStyle.zoom = 1, 
   8: this.runtimeStyle.backgroundImage = "none" ) ); } 

CSS에 이런식으로 넣어주면 한꺼번에 페이지내 모든 투명 배경이미지를 제어할수있다.

발견된 문제점으로는 투명png 배경이미지가 있는 레이어위에 z-index로 다른 레이어를 얹었을때 그안에 있는 모든 링크나 버튼들이 클릭이 안된다는 점이다.

투명배경위에 링크나 메뉴버튼을 넣을 필요가 없는 경우엔 유용한 소스라고 할수있다.

 



Jquery plug-in을 이용한 투명이미지 출력방법도 몇가지 있다.

 

  jquery IE6 png transperency fix

해당싸이트에가서 jqPngFix.zip파일을 다운받아 적용한다. 배경은 지원이 되지않으며, 싸이트내 단순 .img 태그에만 적용한다.

   

jquery.pngFix.js PNG-Transparency

IE 5.5와 6을 지원하며, background에도 png를 적용할수있으나, repeat이나 position속성등은 쓸수없고

예전의 그것과는 약간 다른 느낌의 fliker현상이 발견되었다.

항상 png이미지가 포함되는 요소의 width와 height를 지정 해주어야 한다.

 

iFixPng improved

background-position은 지원하나 repeat은 지원이 안된다. 최신 버전에서는 background-position을 퍼센티지로도 지정할수있다.

 

 

 

마지막으로 jquery 플러그인은 아니지만 현재 블로그에 적용하고있는 소스를 소개해본다. 

 적용했었는데, 텍스트큐브엔 자바스크립트를 업로드 할수없어 다른데서 끌어쓰다가 그냥 없애버렸기때문에 현재 IE6에서는 블로그 투명테두리가 안보이도록 바꿔버렸다.

 DD_belatedPNG

7kb가량의 자바스크립트를 로드해야되지만(7kb가 무겁다는 얘기는 절대 아니다), 셀랙트박스, 라디오버튼, 이미지hover, javascript animation등에도 자유자재로 png투명이미지를 배경이나 버튼이미지로 넣을수있다.

광범위한 지원과 더불어 개발자의 끊임없는 업데이트도 눈에 띈다.

물론 fliker현상도 없다!


개인적으로는 첫번째와 마지막 소스를 추천하고싶다.
Posted by 수라