접근성을 해치지 않는 자바스크립트의 사용
자바스크립트에 대한 잘못된 생각
자바스크립트 없이는 개발을 할 수 없다?
많은 개발자들이 자바스크립트가 없이는 개발을 할 수 없다고 생각한다. 그만큼 자바스크립트를 일상적으로 많이 사용하지만 자바스크립트를 과용하는 경우가 많다는 것이다. 자바스크립트는 클라이언트 환경에서 작동하기 때문에 핵심 기능에 사용해서는 안된다. 핵심 기능은 서버사이드 언어로 처리를 하고 자바스크립트는 그 옆에서 UI구성을 위해서 도와주는 역할을 해야 한다. 바꿔 말하면 자바스크립트의 도움 없이도 핵심 기능은 작동을 해야 한다. 먼저 자바스크립트없이 HTML과 서버사이드 언어만으로 기능이 작동 되게 개발을 하고 자바스크립트를 이용해서 좋은 UI나 유효성 검사 등을 추가하는 순서로 만들어야 한다. 만약 이러한 방식으로 구현되지 않고 자바스크립트를 핵심 기능의 일부로 사용하면 접근성, 사용성이 떨어지는 것 뿐만 아니라 보안도 떨어지고 데이터의 무결성도 보장되지 않는다.
자바스크립트가 작동하지 않는 환경도 고려를 해 줘야 하는가?
자바스크립트가 작동하지 않는 환경이 일반적인 경우는 아니지만 스크립트를 사용할 수 없는 환경에 대한 고려는 필요하다. 실제로 브라우저들은 서로 자바스크립트 엔진이 다르기 때문에 개발 환경에서는 잘 작동하던 기능이 어떤 사용자 환경에서는 작동하지 않을 수 있다. 그리고 사용자 중에서도 보안이나 네트웍 전송량 등의  이유로 스스로 자바스크립트 기능을 끄고 사용하는 경우도 있다. 실제로 야후에서 분석한 결과에 따르면 약 2%정도의 사용자가 자바스크립트를 사용할 수 없는 상황에서 야후 사이트를 이용한다고 한다. 또한 WEB AIM에서 스트린 리더 사용자를 대상으로 한 설문 결과를 보면 약 1.6%의 사용자가 자바스크립트를 끄고 웹을 사용한다고 한다. 2%의 사용자 수가 작아보일 수도 있지만 전체 사용자 수의 2%라고 하면 규모가 큰 사이트에서는 절대로 무시할 수 있는 수의 사용자이다.
서버 부하를 줄이기 위해서 자바스크립트로만 유효성 검사를 한다?
자바스크립트를 이용해서 서버의 부하를 줄일 수 있다는 것은 널리 알려진 지식이다. 자바스크립트로 선처리를 행함으로서 네트웍이나 서버의 처리를 감소시킨다는 것인데 이것을 잘못 이해하여 서버에서 검증할 필요 없이 자바스크립트만으로 유효성을 체크하는 것이 좋다고 생각하는 사람들이 있다. 사용자측으로 부터 넘어온 모든 값은 그 값의 유효성을 완전히 보장할 수 없기 때문에 서버측에서도 유효성 체크를 반드시 해 줘야만 한다. 이것은 서버의 부하를 높이는 것 이전에 자료의 무결성을 보장하는 중요한 과정이다. 자바스크립트를 거치지 않고 서버에 임의로 변조된 값을 보내는 일은 아주 쉬운 일이다.
자바스크립트를 사용하지 않으면 UI가 불편해 진다?
자바스크립트를 이용해서 RIA나 좋은 UI를 만들 수 있는 것은 사실이지만 웹환경을 이해하고 일반적인 웹 인터페이스를 이용해서 만드는 것이 더 좋은 UI를 제공할 수 있다. 사용자 친화적인 UI에 대한 고민을 해야지 자바스크립트를 사용했다고 좋은 UI가 나오는 것은 아니다. 실제적으로 가장 사용자가 이해하기 쉬운 UI는 사용자 OS나 브라우저에서 기본적으로 제공하는 컨트롤 인터페이스를 그대로 사용하는 것이고 이는 자바스크립트 없이도 충분히 가능하다.
자바스크립트는 사용자 환경에 내려보내지고 사용자의 브라우저에서 실행이 되기 때문에 이에 의존해서 프로그램을 만들게 되면 보안, 접근성에 문제가 생기기 쉽다. 이러한 자바스크립트의 특징을 정확히 이해하지 못한 잘못된 개발 방법이나 상식들 때문에 자바스크립트가 오용되고 있는 경우가 많다. 자바스크립트는 어디까지나 보조적인 수단이라는 것을 이해하고 핵심적인 기능을 해치지 않는 한도에서 사용하는 것이 중요하다.

자바스크립트 선언
<script language="Javascript">
//code
</script>
자바스크립트는 스크립트(script) 요소로 선언을 한다. 모든 스크립트 요소에는 타입(type)을 명시해 주어야 하고 자바스크립트의 타입은 "text/javascript" 이다. 많은 경우 language 속성 만을 선언해서 자바스크립트버젼을 명시하는데 반드시 타입을 명시를 해 주어야 한다.
<script type="text/javascript">
//code
</script>

링크 요소(a element)의 href 속성과 자바스크립트의 사용
href 속성은 Hypertext REFerence의 약자이고 hypertext의 위치를 나타내는 URI를 그 값으로 갖는다. 하지만 많은 경우 "javascript:myFunction()"과 같이 잘못된 값을 이용하는 것을 볼 수 있다. 이와 같이URI가 아닌 잘못된 값이 들어가게 될 경우 브라우저에서 제공하는 북마크나 새창, 새탭으로 열기 등의 기능들이  작동하지 않게 된다.  따라서 href의 값은  항상 유효한 URI가 들어가도록 하고 자바스크립트 적용은 onclick과 같은 이벤트 속성을 통해서 해야 한다.
의미 없는 href 값을 사용한 경우
사용자의 클릭이 링크와 관련이 있는 기능을 한다면 우선은 자바스크립트 없이도 페이지를 이동 할 수 있게 href에 적합한 값을 넣어 주어야 한다. 예를 들어서 탭 콘텐츠를 사용할 경우 탭을 누르면 해당 탭과 관련있는 컨텐츠로 이동할 수 있게 페이지내의 링크를 사용하면 된다. href 안의 값으로 페이지 안에서의 해당 컨텐츠 앵커 주소를 넣는 것으로 간단히 구현 된다.
<a href="#notice-list">
    <img src="notice-tab.gif" alt="Notice" />
</a>
그리고 이 마크업을 기본으로 하여 이벤트 속성으로 원하는 기능을 넣어주면 된다.
<a href="#notice-list" onclick="showNoticeTab(); return false;">
    <img src="notice-tab.gif" alt="Notice" />
</a>
클릭을 했을 때 자바스크립트로 탭을 보여준 후 false를 리턴하여 해당 앵커로 이동하지 않도록 처리 한다. 자바스크립트가 작동 할 때에는 정상적인 탭 콘텐츠 형태로 작동 할 것이고 그렇지 않을 경우에는 해당 컨텐츠로 이동을 하여 접근성을 유지할 수 있다.
만약 자바스크립트가 링크와 관련이 없는 경우에는 a 요소를 사용하기 보다는 버튼(button) 요소를 사용해서 해서 스크립트를 적용하면 안된다. 보통 스타일을 조정해서  효과를 주는 것이 이러한 것에 해당하게 되는데 이 경우는 자바스크립트가 작동을 하지 않아도 컨텐츠 이해에 크게 문제가 되지 않는 경우이다.
<button onclick="myAction()">
    <img src="button.gif" alt="보기" />
</button>

버튼 요소는 브라우저에서 버튼 모양으로 표현이 되는데 스타일로 버튼 모양을 없앨 수 있으므로 필요에 따라서 사용하면 된다.
팝업창을 열 때(window.open)
<img src="openWindow.gif" onclick="window.open('popup.html', '', 'widht=300,height=200')">
<a href="#">
    <img src="openWindow.gif" onclick="window.open('popup.html', '', 'widht=300,height=200')">
</a>
href에 #을 넣고 onclick 안의 스크립트에 경로를 처리하는 경우가 있는데 팝업창은 페이지가 별도로 존재 하기 때문에 a 요소를 이용해서 href에 적절한 팝업창의 경로는 넣어서 구현하여야 한다.
<a href="popup.html" onclick="window.open(this.href, 'popupName', 'width=300,height=200'); return false;">
    <img src="openWindow.gif">
</a>
이럴 경우 사용자가 자신의 의도 대로 팝업창을 새창, 새탭 등으로 열 수 있고 심지어 즐겨 찾기도 할 수 있다.

자바스크립트를 이용한 페이지 이동
웹사이트를 이용하다 보면 서식에서 값을 입력하고 전송을 하는 순간 "따다다닥" 하는 식으로 클릭을 여러번 한 것과 같은 소리가 나는 경우를 접하게 된다. 서식 입력을 처리하는 과정이 여러페이지에 걸쳐서 일어나게 되는데 이 처리를 자바스크립트로 하게 되면 이런 현상이 발생한다.
<script type="text/javascript">
document.location.href="redirection.html";
</script>
위와 같이 페이지를 이동 하거나 아래와 같이 서식 요소를 이용해서 값을 넘기는 경우가 이러한 경우이다.
<form name="login_form">
    <input type="hidden" name="user_id" value="myid" />
    <input type="hidden" name="user_pwd" value="mypassword" />
    <input type="hidden" name="redirect_url" value="/login/" />
    <input type="hidden" name="somevalue" value="blahblah" />
    ...
</form>
<script type="text/javascript">
f = document.forms.login_form;
f.action = "http://login.oursite.com/login/";
...
f.submit();
</script>
심한 경우 아래와 같이 전혀 의미 없는 서식을 이용하기도 한다.
<form method="post" name="sg_form" action="http://www.qubi.com/" target="_top">
</form>
<script> sg_form.submit(); //3</script>
위와 같은 페이지들은 적절하게 구성되지 않은 HTML 페이지이기 때문에 특정 환경에서 작동을 안 할 수도 있다. 서식 요소나 스크립트 요소는 상위에 바디(body)나 헤드(head) 요소가 있어야 하는데 위와 같은 경우 이러한 요소가 없기 때문에 HTML로 해석이 안되어 스크립트가 작동 되지 않거나 값이 넘어가지 않을 수도 있다. 그리고 서식 요소 하위에 전송 기능을 하는 인풋 요소가 없기 때문에 자바스크립트로 전송이 일어나지 않을 수도 있다.
이와 같이 페이지를 이동하거나 값을 넘길 필요가 있을 때 자바스크립트에 의존해서 이를 처리하게 되면 클라이언트의 환경에 따라서 동작이 실패할 수 있다. 따라서 이러한 처리는 자바스크립트에서 처리 하지 말고 서버 측에서 처리를 하는 것이 더욱 안정적이다.
이러한 중간과정에서의 처리를 서버측에서 모두 처리 하는 것이 가장 바람직 하지만 어쩔 수 없이 사용을 해야할 경우에는 - 그럴 경우가 많지는 않겠지만 기존의 호환성을 위해서 - DOCTYPE 선언이나 html 요소, head, body와 같은 필수 엘리먼트들이 존재하는 완성된 페이지를 사용 하도록 하고, 자바스크립트가 작동하지 않는 경우를 위해서 서식 요소에 전송 버튼도 제공을 하고, 결과 메세지도 alert외에 일반 텍스트와 다음 페이지 이동 링크를 제공하도록 해야 한다.
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr" />
<title>Redirect</title>
</head>
<body>
<script type="text/javascript">
/*
 some processes...
*/
alert('이래저래한 이유로 다시 돌아 갑니다.');
document.location.href="redirection.html";
</script>
<p><a href="redirection.html">이래저래한 이유로 다시 돌아 갑니다.</a></p>
</body>
</html>
캐릭터 셋 선언이 없는 경우 브라우저의 기본 설정으로 alert이 작동하기 때문에 브라우저의 기본 설정이 ko-kr이 아닌 경우 한글이 깨지게 된다. 문서의 마임타입(mime-type)도 text/html인지 확인해야 한다.

서식 요소에서의 자바스크립트 사용
일반적으로 서식은 사용자가 입력한 값을 서버측에 전달하는 역할을 하고 그 전달은 서식 요소의 전송 기능을 통해서 이루어 진다. 이러한 서식을 구현 할 때에 자바스크립트를 사용하는 경우가 많다.
전송(submit)
서식은 값을 보내는 전송 기능을 제공하고 있다. <input type="submit" />이나 <input type="image" />, <button type="submit></button>이 전송 기능을 하는 컨트롤인데 서식의 값 유효성 체크를 하는 과정에서 이러한 서식의 자체적인 전송 기능을 이용하지 않고 자바스크립트로 서식 전송을 하는 경우가 있다.
<script type="text/javascript">
function submitForm() {
    loginForm.submit();
}
</script>
<form id="loginForm" name="loginForm" action="">
    User Id <input type="text" name="loginId">
    User Password <input type="password" name="loginPassword"><br>
    <img src="login.gif" onclick="submitForm()">
</form>
위와 같은 경우 서식에 전송 기능이 없기 때문에 브라우저에 따라서 script로 전송이 안되는 경우도 있고 전송 버튼 대신에 이미지가 들어있기 때문에 의미적으로도 맞지 않다. 따라서 서식을 제작할 때에는 반드시 전송 기능을 적절한 HTML 요소를 이용해서 제공해야 한다.
<form id="loginForm" name="loginForm" action="">
    <p>
        <label for="loginId">User Id</label>
        <input type="text" id="loginId" name="loginId" /><br />
        <label for="loginPassword">User Password</label>
        <input type="password" id="loginPassword" name="loginPassword" />
    </p>
    <p>
        <input type="image" src="login.gif" alt="Login" />
    </p>
</form>

유효성 검사(validation)
클라이언트 측에서 자바스크립트를 이용한 유효성 검증은 자바스크립트가 서식을 전송(form.submit())하는 방식 대신에 서식의 전송 이벤트(onsubmit)를 캐치하는 방식으로 구현한다.
<script type="text/javascript">
function submitForm() {
    if (!loginForm.loginId.value) {
        alert("아이디를 넣어주세요.");
        loginForm.loginId.focus();
    } else if (!loginForm.loginPassword.value) {
        alert("비밀번호를 넣어주세요.");
        loginForm.loginPassword.focus();
    } else {
        loginForm.submit();
    }
}
</script>
<form id="loginForm" name="loginForm" action="">
    아이디 <input type="text" name="loginId">
    비밀번호 <input type="password" name="loginPassword"><br>
    <img src="login.gif" onclick="submitForm()">
</form>
위와 같은 경우 자바스크립트만을 이용해서 서식을 전송하고 있기 때문에 HTML만으로는 기능이 작동하지 않는다.
<script type="text/javascript">
function submitForm(formEl) {
    //TrimAll(formEl);

    var errorMessage = null;
    var objFocus = null;

    if (formEl.loginId.value.length == 0) {
        errorMessage = "아이디를 넣어주세요.";
        objFocus = formEl.loginId;
    } else if (formEl.loginPassword.value.length == 0) {
        errorMessage = "비밀번호를 넣어주세요.";
        objFocus = formEl.loginPassword;
    }

    if(errorMessage != null) {
        alert(errorMessage);
        objFocus.focus();
        return false;
    }
    return true;
}
</script>

<form id="loginForm" name="loginForm" action="" onsubmit="return submitForm(this)">
    <label for="loginId">아이디</label> <input type="text" id="loginId" name="loginId" />
    <label for="loginPassword">비밀번호</label> <input type="password" id="loginPassword" name="loginPassword" /><br />
    <input type="image" src="login.gif" alt="Login" />
</form>
이와 같이 onsubmit 이벤트를 이용해서 서식의 유효성을 검사하고 그 결과를 true나 false로 보내줌으로써 서식이 전송을 진행하거나 멈출 수 있고, onsubmit 이벤트가 발생하지 않아도 사용자는 서식을 사용할 수 있기 때문에 접근성이 높아지게 된다.

게시판 등에서 페이지 이동을 자바스크립트로 하는 경우
게시판에서 페이지의 이동을 자바스크립트 서식 전송으로 하는 것을 많이 볼 수 있다. 아래와 같이 사용자 인풋이 없는 빈 서식을 하나 만들고 이것과 자바스크립트를 이용해서 페이지를 이동하는 것이다.
<form method="post" name="vars">
    <input type="hidden" name="articleId" value="23" />
    <input type="hidden" name="page" value="3" />
    <input type="hidden" name="keysord" value="" />
    <input type="hidden" name="searchType" value="" />
    <!-- 등등 -->
</form>

...

<a href="javascript:ArticleRead()">글읽기</a>
<a href="javascript:GoList()">리스트 보기</a>
URL이 간단해 지고 다루기 쉽다는 이유로 이러한 방식으로 개발을 하는 경우가 많은 것 같다. 위와 같이 모든 기능을 자바스크립트를 이용해서 구현을 하게 되면 자바스크립트 오류가 있거나 자바스크립트가 작동 하지 않는 상황에서는 접근을 할 수 없게 된다. 또한 모든 변수를 POST를 통해서 전달하기 때문에 글의 주소를 나타내는 URL이 표시되지 않고 해당 페이지를 따로 북마크 한다든지 링크를 저장을 할 수 없게된다. 게시판의 경우 해당 게시물로의 접근을 쉽게 해 주어야 하는데 사용자가 URL을 알 수 없게 함으로써 접근을 원천적으로 막게 된다.
자바스크립트를 이용하지 않고도 a 요소와 URL만으로도 작동 가능한 페이지를 만들고 쿼리스트링을 효율적으로 다루는 방법을 모색하여 개발을 진행하는 것이 좋다.

마치며
웹사이트 개발을 하면서 접할 수 있었던 자바스크립트 과용 예를 적어 보았다. 그런데 놀라운 것은 이러한 개발 방식을 초보부터 어느정도 경력이 된 개발자들까지 아무런 고민 없이 사용하고 있었다는 것이다. 책이 잘못된 것인지 교육이 잘못 된 것인지 정확한 원인을 알 수는 없지만 많은 개발자들이 웹이 가지고 있는 기본적인 특성을 무시한채 이러한 방법으로 개발을 하고 있는 것이 사실이다. 그리고 초보 개발자들은 HTML을 잘 모르기 때문에 이러한 개발 방식을 아무 고민 없이 그냥 받아들이고 있는 실정이다.
접근성 뿐만 아니라 사용성도 크게 낮추고 있는 것이 바로 이 잘못된 자바스크립트의 사용이다. 부디 개발자들이 올바른 HTML에 기초한 접근성 높은 웹사이트, 웹 어플리케이션을 구축 하기를 바라는 바이다.
참고

    웹 접근성을 위한 자바스크립트 적용 방법 (Graceful Degradation vs. Progressive Enhancement)
    겸손한 Javascript 및 Ajax 코드 작성 안내서

'자바스크립트' 카테고리의 다른 글

자바스크립트 MVC 패턴 구현 하기.  (0) 2012.08.20
순수 HTML typing 게임  (0) 2012.08.16
물고기 소스  (0) 2012.06.15
document.createElement  (1) 2012.06.14
event.keyCode 사용 하기.  (0) 2012.06.13
Posted by 사라링

Dialog

 | AJAX
2012. 6. 19. 14:22

호출부

$("#popupBtn").on("click", function(){
            Page.popup({
                url : "/common/popup/zipPop",
                width : "500",
                height : "400",
                title :"우편번호 조회",
                close : function(result){   
                    if(result.addr1 !=""&&result.addr1 !=null){
                        $("#addr1_std").val(result.addr1);
                        $("#zip_std").val(result.zipcode);
                    }
                }
            });

        });       



구현부

Page.popup = function(opt){
    var dlgid = "dlg"+Math.floor(Math.random()*1000000);
    opt.data = opt.data ? opt.data : {};
    opt.data.dlgid = dlgid;
    var modal = false;
    if(opt.modal){
        modal = opt.modal;
    }
    $.ajax({
        url : opt.url,
        data : opt.data,
        async : false,
        type : "post",
        dataType : "html",
        success : function(result){
            var popup = $("<div/>").attr("id", dlgid);
            $("body").append(popup);
           
            popup.html(result);
            popup.dialog({
                title: opt.title,
                resizable: true,
                modal: modal,
                width: opt.width ? opt.width : 300,
                height: opt.height ? opt.height : 300
            }).on("dialogclose", function(e, data){
                $(this).remove();
                if( opt.close ) opt.close(data);
                popup.dialog("destroy");
            });
        },
        error : function(res){
            Page.parseError(res.responseText);
        }
    });
};


    $("#"+dlgid).trigger("dialogclose", {
                zipcode: $(this).data("zipcode"),
                addr1 : $(this).data("addr")
            });


아작스 호출

$.ajax({
                type : "POST",
                url : "/common/popup/zipListPop",
                dataType : "json",
                data : { sch : $("#iSearch").val()},
                success : function(data){
                    $("#ziptbl tbody").html("");
                    if(data.length > 0){
                        $.each(data, function(idx, row){
                            var tr = $("<tr><td/><td class='txt_l'/></tr>");
                            var data = {
                                zipcode : row.zipcode,
                                addr : row.addr
                            };
                            tr.data(data).addClass("zipcodeList");
                            tr.find("td:eq(0)").text(row.zipcode);
                            tr.find("td:eq(1)").text(row.addr);
   
                            $("#ziptbl tbody").append(tr);
                        });
                    }else{
                        $("#ziptbl tbody").html("<tr><td colspan='2' height='40'>검색된 자료가 없습니다.</td></tr>");
                    }
                }

'AJAX' 카테고리의 다른 글

PJax ?  (0) 2012.08.24
Ajax 란  (0) 2012.05.24
AJax JSON 데이터 가져오기의 형식 .  (0) 2012.05.24
Posted by 사라링

PHP는
<?

header("Content-Type: application/vnd.ms-excel");

?>

JSP는

<%@ page contentType="application/vnd.ms-excel; name='My_Excel'" %>
<%
response.setHeader("Content-Disposition", "inline; filename=myfile.xls");
response.setHeader("Content-Description", "JSP Generated Data");
%>

저 부분을 <HTML> 태그 앞에 넣으면 끝나지요.
저 페이지가 호출이 되면 오피스가 깔려있는 사용자들은 저장할것인지 그냥 열것인지를 물어보구여, 안깔려 있는 사용자들은 파일을 다운받을수 있게 되지요.


그럼 워드 파일은
<?
header("Content-Type: application/msword");
?>

파워포인트 역시 같은 방법으로
<?
header("Content-Type: application/vnd.ms-powerpoint");
?>


그럼 마지막으로 ASP에서는
<%
Response.Buffer = TRUE
Response.ContentType = "application/vnd.ms-excel"
%>


다음은 header 내용을 변경해서 excel로 바꾸어 주는 구문입니다.

* excel.php

<?php

header("Content-type: application/vnd.ms-excel");

header("Content-Disposition: attachment; filename=test.xls");

header("Content-Description: PHP4 Generated Data");

?>

<html>

<body>

<table>

<tr>

<td>테스트1</td>

<td>테스트1</td>

<td>테스트1</td>

<td>테스트1</td>

</tr>

<tr>

<td>테스트2</td>

<td>테스트2</td>

<td>테스트2</td>

<td>테스트2</td>

</tr>

</table>

</body>

</html>



실행시켜보세요. 어떻게 되죠? test.xls 이름으로 excel 화일이 다운로드 되죠.

혹 DB내용을 excel형태로 출력해야될 때 유용할거 같습니다








[JSP] 쿼리결과를 엑셀로 추출
<%@ page contentType="application/vnd.ms-excel;charset=euc-kr" import="java.sql.*,java.text.*"%><%

response.setHeader("Content-Disposition", "inline; filename=myfile.xls"); // 파일 이름 지정
response.setHeader("Content-Description", "JSP Generated Data");

Connection con = null ;
Statement st = null ;
ResultSet rs = null ;


try{
con = ## 컨넥션 얻기 ##
st = con.createStatement();
rs = st.executeQuery("## 쿼리 ##");
ResultSetMetaData rsmd = rs.getMetaData();

%><html>
<body bgcolor=white>
<table border=1>
<tr bgcolor="#CACACA">
<% for ( int i = 1 ; i <= rsmd.getColumnCount() ; i ++ ) { %>

<th><%=rsmd.getColumnName(i)%></th>

<% } %>
</tr>
<%
while(rs.next()) {
%>
<tr>
<% for ( int i = 1 ; i <= rsmd.getColumnCount() ; i ++ ) { %>

<td><%

if ( rs.getString(rsmd.getColumnName(i)) == null ) {
out.print("");
} else {

out.print(rs.getString(rsmd.getColumnName(i)));
}

%></td>

<% } %>
</tr>
<% } %>
</table>
</body>
</html>
<%


} catch (Exception eee) {}
finally {
if ( rs != null ) rs.close();
if ( st != null ) st.close();
if (con != null ) con.close;
}
%>

JQuery 이용해서 Excel 파일로 저장하기. javascript  ASP

2011/06/15 09:59

복사 http://blog.naver.com/hogini/10111306100

기존에는 a.asp가 있고 그것을 excel로 저장하기 위해선 같은 a.asp 파일을 복사하여 a_e.asp를 만들고

a_e.asp의 상단 부분에 다음과 같은 구분을 삽입했다.

이럴경우 a.asp의 버튼이나 잡다한 것 까지 죄다 excel로 저장되어 지저분해지고. a_e.asp만 따로 해서 편집하자니

a.asp가 자주 변경되면 그것 또한 짜증이였다.

 

 <%
 Response.Buffer = true
 Response.AddHeader "Content-Disposition","attachment;filename=each_week_data.xls"
 Response.ContentType = "application/vnd.ms-excel"
 Response.CacheControl = "public"
%>

해서. JQuery를 사용해보니 훨씬 간편하고 아주 좋았다!

<form>에서 아래와 같이 onsubmit부분에 $("#excel_val")이라는 id, 즉 post로 넘겨줄 hidden값에 원하는구역에 <div>감싸고 그 id값.html()로

해당 <div> 아래의 모든 태그를 가지고 온다.

그리고 submit으로 a_e.asp로 날려주면 끝.

a_e.asp에선 request로 받아주면 된다.

또 하나 맘에 드는점은 jquery로 각종 스타일을 주고 excel 저장했던 기존방법은 html에선 잘되는데 엑셀로 저장하면 스타일이 안먹는 경우가

많았지만 jquery로 하니 현재 보이는 html상태를 excel에서 거의 그대로 저장하니 아주 만족!!

 

 a.asp

 

<div id="excel_view">

  <table>

...

  </table>

</div>

<input type="button" value="Excel" onclick="excel_save()" /> <!--엑셀 저장 버튼-->

<!--엑셀로 저장-->
<form action="a_e.asp" method="post" target="_blank" onsubmit='$("#excel_val").val($("#excel_view").html())' id="exe">
 <input type="hidden" name="excel_val" id="excel_val" />
</form>
<script type="text/javascript">
    function excel_save(){
    $("#exe").submit();
    }
</script>
<!--엑셀로 저장 끝-->


 

a_e.asp

 

<%
 Response.Buffer = true
 Response.AddHeader "Content-Disposition","attachment;filename=each_week_data.xls"
 Response.ContentType = "application/vnd.ms-excel"
 Response.CacheControl = "public"
%>

<html xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<style type="text/css">
body {font-family:tahoma;font-size: 12px}
table {padding:2px;border-spacing:0px;font-family:tahoma;font-size: 12px;border-collapse: collapse}
input,textarea,Select {font-family:tahoma;font-size: 12px;border-collapse: collapse;}
.bgc {background-color:#dddddd}
.bgct {background-color:#FAF082}
td {text-align:center}
br {mso-data-placement:same-cell;}

</head>
<body>
<%=request("excel_val")%>
</body>

 


JSP

jQuery 를 이용해서 HTML 테이블을 엑셀로 저장하는 간단한 방법입니다.

다음은 HTML 코드입니다.

<form action="/SaveToExcel.jsp" method="post" target="_blank"
    onsubmit='$("#dataToDisplay").val( $("<div>").append( $("#ReportTable").eq(0).clone() ).html() )'
>
    <pre><input type="image" src="/images/icons/save_excel.png"></pre>
   <pre><input type="hidden" id="dataToDisplay" name="dataToDisplay" />
    <table id="ReportTable">
    ... 중략
    </table>
</form>

설명
reportTable - 저장하기 원하는 테이블 ID
dataToDisplay - 서버로 POST될 베이블을 위한 hidden변수


폼의 onSubmit시에 저장할 HTML 테이블을 jQuery 메서드로 쉽게 처리할수 있다.


<table>을 포함한 HTML코드를 가져오는 부분의 처리가 중요하다.

jQuery.html() 메서드는 innerHTML만 가져오므로  table id를 기준으로 실행하면 <table> 태그가 빠지게 된다.

그래서 <div> 안에  전체 <table> 을 append하면  <div> <table>...</table> </div>  가 되고

여기서  .html() 을 실행하면  <table>...</table> 을 리턴하므로 원하는 결과를 얻을 수 있다.


다음은 서버쪽의 코드를 Jsp의 예로 보면 다음과 같다.


<%
response.setContentType("application/vnd.ms-excel; name='excel'");
response.setContentDisposition("filename=export.xls");
// Fix for crappy IE bug in download.
response.setHeader("Pragma","");
response.setHeader("Cache-Control","");

%>
<html>
<head></head>
<body>
${param.dataToDisplay}
</body>
</html>




'JSP' 카테고리의 다른 글

페이징 처리. JSP 설명까지 포함  (2) 2012.11.01
Problems warning 를 제거 하자.  (1) 2012.10.23
정규표현식 공식 및 응용 .  (0) 2012.05.08
기본JDBC 만들기  (0) 2012.05.08
Tiles(레이아웃처리)  (0) 2012.05.08
Posted by 사라링

코드는 아래와 같습니다.

<html>
<head>
<script type="text/javascript">
function getIndex()
  {
  var x=document.getElementById("mySelect");
  alert(x.options[x.selectedIndex].value);
  }
</script>
</head>
<body>
Select your favorite fruit:
<select id="mySelect">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="pineapple">Pineapple</option>
  <option value="banana">Banana</option>
</select>
<br /><br />
<input type="button" onclick="getIndex()"
value="Alert index of selected option">
</body>
</html>

이 소스는 인터넷에 있는 소스를 약간 수정하여서 써보았다.
원본소스는 아래의 링크로 가보면 있다.
http://www.w3schools.com/htmldom/prop_select_selectedindex.asp

EditPlus 혹은 기타 편집기 (Notepad도 좋다.) 에 소스를 복사하여 넣은뒤에
적당한 이름을 붙이고 html 파일로 저장해보자.

그리고 html 파일을 실행하여보면

사용자 삽입 이미지


'J-Query' 카테고리의 다른 글

body CSS 그라데이션 흰색 - > 블랙  (0) 2012.06.22
jQuey eq form 값 반디 모음 1  (0) 2012.06.22
Build CRUD Application with jQuery EasyUI  (0) 2012.06.14
슬라이드 시계  (0) 2012.06.13
JQuery 시계  (0) 2012.06.13
Posted by 사라링

물고기 소스

2012. 6. 15. 09:37


물고기가 돌아 다니며. 마우스 클릭시 먹이가 생겨 물고기가 모여 든다


<object type="application/x-shockwave-flash" style="outline:none;" data="http://hosting.gmodules.com/ig/gadgets/file/112581010116074801021/fish.swf?" width="300" height="200"><param name="movie" value="http://hosting.gmodules.com/ig/gadgets/file/112581010116074801021/fish.swf?"></param><param name="AllowScriptAccess" value="always"></param><param name="wmode" value="opaque"></param><param name="scale" value="noscale"/><param name="salign" value="tl"/></object>
     

를 소스 에 추가 하면 끝 /

Posted by 사라링

Build CRUD Application with jQuery EasyUI

Tutorial » Build CRUD Application with jQuery EasyUI

It has become a common necessily for web application to collect data and manage it properly. CRUD allows us to generate pages to list and edit database records. This tutorial will show you how to implement a CRUD DataGrid using jQuery EasyUI framework.

We will use following plugins:

  • datagrid: show the user list data.
  • dialog: create or edit a single user information.
  • form: used to submit form data.
  • messager: to show some operation messages.

Step 1: Prepare database

We will use MySql database to store user information. Create database and 'users' table.

Step 2: Create DataGrid to display user information

Create the DataGrid with no javascript code.

  1. <table id="dg" title="My Users" class="easyui-datagrid" style="width:550px;height:250px"  
  2.         url="get_users.php"  
  3.         toolbar="#toolbar"  
  4.         rownumbers="true" fitColumns="true" singleSelect="true">  
  5.     <thead>  
  6.         <tr>  
  7.             <th field="firstname" width="50">First Name</th>  
  8.             <th field="lastname" width="50">Last Name</th>  
  9.             <th field="phone" width="50">Phone</th>  
  10.             <th field="email" width="50">Email</th>  
  11.         </tr>  
  12.     </thead>  
  13. </table>  
  14. <div id="toolbar">  
  15.     <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>  
  16.     <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>  
  17.     <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a>  
  18. </div>  

We don't need to write any javascript code and we can show the user list as following image:

The DataGrid use the 'url' property that is assigned to 'get_users.php' to retrieve data from server.

Code of get_users.php file

  1. $rs = mysql_query('select * from users');  
  2. $result = array();  
  3. while($row = mysql_fetch_object($rs)){  
  4.     array_push($result, $row);  
  5. }  
  6.   
  7. echo json_encode($result);  

Step 3: Create form dialog

To create or edit a user, we use the same dialog.

  1. <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"  
  2.         closed="true" buttons="#dlg-buttons">  
  3.     <div class="ftitle">User Information</div>  
  4.     <form id="fm" method="post">  
  5.         <div class="fitem">  
  6.             <label>First Name:</label>  
  7.             <input name="firstname" class="easyui-validatebox" required="true">  
  8.         </div>  
  9.         <div class="fitem">  
  10.             <label>Last Name:</label>  
  11.             <input name="lastname" class="easyui-validatebox" required="true">  
  12.         </div>  
  13.         <div class="fitem">  
  14.             <label>Phone:</label>  
  15.             <input name="phone">  
  16.         </div>  
  17.         <div class="fitem">  
  18.             <label>Email:</label>  
  19.             <input name="email" class="easyui-validatebox" validType="email">  
  20.         </div>  
  21.     </form>  
  22. </div>  
  23. <div id="dlg-buttons">  
  24.     <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>  
  25.     <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>  
  26. </div>  

The dialog is created with no javascript code also.

Step 4: Implement creating and editing a user

When create a user, we open the dialog and clear form data.

  1. function newUser(){  
  2.     $('#dlg').dialog('open').dialog('setTitle','New User');  
  3.     $('#fm').form('clear');  
  4.     url = 'save_user.php';  
  5. }  

When edit a user, we open the dialog and load form data from the selected datagrid row.

  1. var row = $('#dg').datagrid('getSelected');  
  2. if (row){  
  3.     $('#dlg').dialog('open').dialog('setTitle','Edit User');  
  4.     $('#fm').form('load',row);  
  5.     url = 'update_user.php?id='+row.id;  
  6. }  

The 'url' stores the URL address where the form will post to when save the user data.

Step 5: Save the user data

To save the user data we use the following code:

  1. function saveUser(){  
  2.     $('#fm').form('submit',{  
  3.         url: url,  
  4.         onSubmit: function(){  
  5.             return $(this).form('validate');  
  6.         },  
  7.         success: function(result){  
  8.             var result = eval('('+result+')');  
  9.             if (result.success){  
  10.                 $('#dlg').dialog('close');      // close the dialog  
  11.                 $('#dg').datagrid('reload');    // reload the user data  
  12.             } else {  
  13.                 $.messager.show({  
  14.                     title: 'Error',  
  15.                     msg: result.msg  
  16.                 });  
  17.             }  
  18.         }  
  19.     });  
  20. }  

Before submit the form, the 'onSubmit' function will be called, in which we can validate the form field value. When the form field values are submited successfully, close the dialog and reload the datagrid data.

Step 6: Remove a user

To remove a user, we use the following code:

  1. function removeUser(){  
  2.     var row = $('#dg').datagrid('getSelected');  
  3.     if (row){  
  4.         $.messager.confirm('Confirm','Are you sure you want to remove this user?',function(r){  
  5.             if (r){  
  6.                 $.post('remove_user.php',{id:row.id},function(result){  
  7.                     if (result.success){  
  8.                         $('#dg').datagrid('reload');    // reload the user data  
  9.                     } else {  
  10.                         $.messager.show({   // show error message  
  11.                             title: 'Error',  
  12.                             msg: result.msg  
  13.                         });  
  14.                     }  
  15.                 },'json');  
  16.             }  
  17.         });  
  18.     }  
  19. }  

Before remove a row, we will display a confirm dialog to let user to determine whether to really remove the row data. When remove data successfully, call 'reload' method to refresh the datagrid data.

Step 7: Run the Code

Run the code in your browser with MySQL started.

So, you now know the basics of CRUD in jQuery EasyUI framework. Press below link to start the demo application.

Download the EasyUI example:


'J-Query' 카테고리의 다른 글

jQuey eq form 값 반디 모음 1  (0) 2012.06.22
select 태그에서 선택된 option 값 알아보기  (1) 2012.06.15
슬라이드 시계  (0) 2012.06.13
JQuery 시계  (0) 2012.06.13
조작하려는 엘리먼트 선택하기  (0) 2012.06.07
Posted by 사라링


document.createElement

« Gecko DOM Reference

요약

지정된 태그이름을 가지는 엘리먼트를 생성합니다.

문법

엘리먼트 = document.createElement(태그이름);
  • 엘리먼트 생성된 엘리먼트 객체입니다.
  • 태그이름 생성할 엘리먼트의 종류를 지정하는 문자열입니다. 생성된 엘리먼트의 nodeName 속성은 태그이름에 지정된 값으로 초기화됩니다.

예제

이 예제는 새로운 <div> 엘리먼트를 생성한 후, id가 "org_div1" 인 엘리먼트 앞에 추가합니다:

<html>
<head>
<title>||엘리먼트 사용하기||</title>
</head>

<script type="text/javascript">
var my_div = null;
var newDiv = null;

function addElement()
{
  // 새로운 div 엘리먼트를 만들고
  // 내용을 작성합니다.
  newDiv = document.createElement("div");
  newDiv.innerHTML = "<h1>안녕! 반가워!</h1>";

  // 생성된 엘리먼트를 추가합니다.
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(newDiv, my_div);
}

</script>

<body onload="addElement()">
<div id='org_div1'> 위의 문장은 동적으로 만들어 진 것입니다.</div>
</body>
</html>

참고 사항

기본값이 있는 잘 알려진 특성(attributes)들은 자동으로 생성되어 엘러먼트에 특성노드로 추가됩니다.

qualified 이름과 네임스페이스 URI를 갖는 엘리먼트를 만들 경우에는 createElementNS 메서드를 사용합니다.

Gecko 엔진의 createElement 구현은 XUL과 XHTML 문서에 대한 DOM 규약을 따르지 않습니다: localNamenamespaceURInull로 설정되지 않습니다. 자세한 사항은 bug 280692 를 참고하세요.




== 추가

Use jQuery objects to build up your table instead of using string concatenation.  How many time have you seen code similar to the following to build up a table?

        $(function () {

            var content = '';
            content += '<div id="tableWrap">';
            content += '<table id="basicTable">';

            for (var i = 0; i < 200; i++) {


                content += '<tr>';
                content += '<td>';
                content += i;
                content += '</td>';
                content += '<td>';
                content += 200 - i;
                content += '</td>';
                content += '</tr>';
            }

            content += '</table>';
            content += '</div>';

            $('body').append(content);
        });

Let's use jQuery's built in ability to build up the objects and take a look at how we could write this differently below.

        $(function () {

            var $wrap = $('<div>').attr('id', 'tableWrap');

            var $tbl = $('<table>').attr('id', 'basicTable');

            for (var i = 0; i < 200; i++) {

                $tbl.append(
                            $('<tr>')
                                    .append($('<td>').text(i),
                                            $('<td>').text(200 - i))
                           );
            }

            $wrap.append($tbl);
            $('body').append($wrap);
        });

View the live code here!


'자바스크립트' 카테고리의 다른 글

순수 HTML typing 게임  (0) 2012.08.16
자바 스크립트를 이용 할때 꼭 한번 읽어야 할것  (0) 2012.06.20
물고기 소스  (0) 2012.06.15
event.keyCode 사용 하기.  (0) 2012.06.13
window.open(URL,name,specs,replace)  (0) 2012.06.05
Posted by 사라링

=============================================================
키 | 코드(숫자)
=============================================================

←(백스패이스) = 8
TAB = 9
ENTER = 13
SHIFT = 16
CTRL = 17
ALT = 18
PAUSEBREAK = 19
CAPSLOOK = 20
한/영 = 21
한자 = 25
ESC = 27

스패이스 = 32
PAGEUP = 33
PAGEDN = 34
END = 35
HOME =36

←(중간) = 37
↑(중간) = 38
→(중간) = 39
↓(중간) = 40

0 = 48
1 = 49
2 = 50
3 = 51
4 = 52
5 = 53
6 = 54
7 = 55
8 = 56
9 = 57
INSERT = 45
DELETE = 46

A = 65
B = 66
C = 67
D = 68
E = 69
F = 70
G = 71
H = 72
I = 73
J = 74
K = 75
L = 76
M = 77
N = 78
O = 79
P = 80
Q = 81
R = 82
S = 83
T = 84
U = 85
V = 86
W = 87
X = 88
Y = 89
Z = 90

윈도우(왼쪽) = 91
윈도우(오른쪽) = 92
기능키 = 93
0(오른쪽) = 96
1(오른쪽) = 97
2(오른쪽) = 98
3(오른쪽) = 99
4(오른쪽) = 100
5(오른쪽) = 101
6(오른쪽) = 102
7(오른쪽) = 103
8(오른쪽) = 104
9(오른쪽) = 105
.(오른쪽) = 110
/(오른쪽) = 111
*(오른쪽) = 106
+(오른쪽) = 107
-(오른쪽) = 109
F1 = 112
F2 = 113
F3 = 114
F4 = 115
F5 = 116
F6 = 117
F7 = 118
F8 = 119
F9 = 120
F10 = 121
F11 = 122
F12 = 123
NUMLOCK = 144
SCROLLLOCK = 145
=(중간) = 187
-(중간) = 189
`(왼쪽콤마) = 192
(중간) = 220







































사용 하기.

 <input name="adminPW" type="password" value="java" onKeyUp=autoSubmit() tabindex="2" style="width:140px;">


<script language=javascript>
    function send()    {
        if(frm.adminid.value ==""){
            alert("관리자 ID를 입력하세요");
            frm.adminid.focus();
            return false;
        }
        else if(frm.adminpass.value==""){
            alert("관리자 PASS를 입력하세요");
            frm.adminpass.focus();
            return false;
        }
        frm.submit();
}
function autoSubmit(){
    if (event.keyCode == 13)
        send();
}
</script>






이런식으로 13 은 ENTER 키를 누를 시에 send() 를 사용 하라고 지시 하는것.


추가로 ctrl +enter 는

$('#textareaId').keydown(function (e) {

 
if (e.ctrlKey && e.keyCode == 13) {
   
// Ctrl-Enter pressed
 
}
});

방식으로 사용 하면된다.


'자바스크립트' 카테고리의 다른 글

순수 HTML typing 게임  (0) 2012.08.16
자바 스크립트를 이용 할때 꼭 한번 읽어야 할것  (0) 2012.06.20
물고기 소스  (0) 2012.06.15
document.createElement  (1) 2012.06.14
window.open(URL,name,specs,replace)  (0) 2012.06.05
Posted by 사라링

GUI : 그래픽 유저 인터페이스 .

  1. 교육 과정 AWT SWING
  2. NETWORK(소켓, 패킷 ~
  3. 도킹 : 기본 적으로 움직이는 메뉴바. /
  4.  뷰 : 로 만들어짐 이클립스.
  5. 보는 방법에 따라 보여지는것이 다르게 나오는것 을 perspective 라고 함.
  6. perspective미국/영국 [pərspéktiv]

    전망, 원근법, 견해 뜻(5개) 더보기

    오버로딩    : 다중정의 /  ㅠㅠ // 과적 해서 쌓는것 부하가 증가/ 같은 메서드 인데 파라미터가 여러개 인경우 중첩 설계 되는것.

    오버라이딩 :  // 상속 관계에서 가장 가까운 부모 클래스의 디폴트생성자를 갖게 되는것.

윈도우 빌더 설치 하기. // ecliptse -GUI plug-in

http://www.eclipse.org/windowbuilder/download.php  // 위지위그 드래그 drop 하여 사용.

플로그인 방법.

 

help -> Instal new software~ -> add-> ach~..선택 설치. 리스타트.

Eclipse 3.7 (Indigo)

http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7


Eclipse 3.6 (Helios)

http://dl.google.com/eclipse/inst/d2wbpro/latest/3.6


Eclipse 3.5 (Galileo)

http://dl.google.com/eclipse/inst/d2wbpro/latest/3.5

실행 결과 -> new other 시에 windows builder 가 있으면 성공.


Posted by 사라링

슬라이드 시계

2012. 6. 13. 09:31


<!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="en" lang="en"> <head> <title>jQuery Sliding Clock v1.1</title> <style type="text/css"> body { background:#bae1ea url(back.jpg) 50% 0px no-repeat; color:#000; } /* container for clock */ #wrap { position:relative; margin: 100px auto 0; width:700px; height:440px; background:url("slider clock(trans).png") no-repeat top left;
border-style:solid; border-width:1px; overflow:hidden; } /* style background and size of all sliding divs */ #wrap div { position:absolute; margin-left:-700px; width:1400px; height:40px; background:url("slider clock(trans).png") repeat-x; } /* specific position and background position for sliding divs */ #wrap #day { top:40px; background-position:0 -440px; } #wrap #month { top:120px; background-position:0 -480px; } #wrap #date { top:200px; background-position:0 -520px; } #wrap #hour { top:280px; background-position:0 -560px; } #wrap #min { top:320px; background-position:0 -600px; } #wrap #sec { top:400px; background-position:0 -640px; } #title { margin:20px auto; width:550px; text-align:center; } #other { margin:10px auto; width:550px; text-align:center; }
</style> <script type="text/javascript" src="jquery.js"> </script> <script> $(document).ready(function(){ function checktime(olddel){ var now = new Date(); var nowdel = now.getDay() + "|" + now.getMonth() + "|" + now.getDate() + "|" + now.getHours() + "|" + now.getMinutes() + "|" + now.getSeconds(); if ( olddel != nowdel ) { var oldsplit = olddel.split("|"); var nowsplit = nowdel.split("|"); if ( oldsplit[5] != nowsplit[5] ) { clock_slide('#sec',nowsplit[5],11); if ( oldsplit[4] != nowsplit[4] ) { clock_slide('#min',nowsplit[4],11); if ( oldsplit[3] != nowsplit[3] ) { clock_slide('#hour',nowsplit[3],28); if ( oldsplit[2] != nowsplit[2] ) { clock_slide('#day',nowsplit[0],100); clock_slide('#date',(nowsplit[2]-1),22); if ( oldsplit[1] != nowsplit[1] ) { clock_slide('#month',nowsplit[1],57); }; }; }; }; }; }; function clock_slide(which,howmuch,multiple){ $(which).stop().animate({marginLeft: ((howmuch*multiple)-700)+'px'}, 250, 'linear'); }; setTimeout(function(){checktime(nowdel);}, 250); }; checktime("0|0|0|0|0|0"); }); </script> </head> <body> <div id="wrap"> <div id="day"> </div> <div id="month"> </div> <div id="date"> </div> <div id="hour"> </div> <div id="min"> </div> <div id="sec"> </div> </div> <!-- End "wrap" --> <div id="title">jQuery transpearant Slider clock with CSS sprites - by <a href="http://doodleaday.wordpress.com">vonholdt</a></div> <div id="other">Check out my other jQuery clock <a href="http://home.comcast.net/~vonholdt/test/clock/index.htm">here</a></div> </body> </html>

출처 : http://home.comcast.net/~vonholdt/test/clock_slide/index.htm

Posted by 사라링

JQuery 시계

2012. 6. 13. 09:23

jDigiClock

Digital Clock (HTC Hero inspired)

Author: Radoslav Dimov
Version: 2.1 (Changelog)
Download: jdigiclock.zip
Licence: Dual licensed under the MIT and GPL licenses.

Contents

  1. Introduction
  2. Examples
  3. Getting started
  4. Configuration
  5. Compatibility

Introduction

jDigiClock is a jQuery plugin inspired from HTC Hero Clock Widget.

Examples

Bourgas

Clear

Wed, 13 Jun

20°C

20°C

33° / 19°

Bourgas

Sunny and hot

  • Thu

    Warm and humid with some sun

    31° / 17°

  • Fri

    Sunny and humid

    28° / 17°

  • Sat

    Sunny and nice

    26° / 14°

  • Sun

    Sunny and nice

    27° / 14°

reloadWed, 13 Jun, 09:20


Getting started

To use the jDigiClock plugin, include the jQuery library, the jDigiClock source file and jDigiClock core stylesheet file inside the <head> tag of your HTML document:

<link rel="stylesheet" type="text/css" href="css/jquery.jdigiclock.css" />
<script type="text/javascript" src="lib/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="lib/jquery.jdigiclock.js"></script>

To setup jDigiClock, add the following code inside the <head> tag of your HTML document:

<script type="text/javascript">
    $(document).ready(function() {
        $('#digiclock').jdigiclock({
            // Configuration goes here
        });
    });
</script>

jDigiClock accepts a lot of configuration options, see chapter "Configuration" for further informations.

jDigiClock expects a very basic HTML markup structure inside your HTML document:

<div id="digiclock"></div>

Configuration

jDigiClock accepts a list of options to control the appearance and behaviour of the Digital Clock. Here is the list of options you may set:

Property Type Default Description
clockImagesPath string "images/clock/" Clock images path.
weatherImagesPath string "images/weather/" Weather images path.
am_pm boolean false Specifies the AM/PM option.
weatherLocationCode string "EUR|BG|BU002|BOURGAS" Weather location code (see: WeatherLocationDatabase.txt).
weatherMetric string "C" Specifies the weather metric mode: C or F.
weatherUpdate integer 0 Weather update in minutes.
proxyType string "php" Specifies proxy type: php or asp (see: README.txt).

Compatibility

jDigiClock has been tested and works on the following browsers:

  • Internet Explorer 7 (PC)
  • FireFox 3.5 (PC/Linux)
  • Google Chrome 3.0 (PC)
  • Safari 4.0 (PC)

Donate a beer or two via PayPal


'J-Query' 카테고리의 다른 글

Build CRUD Application with jQuery EasyUI  (0) 2012.06.14
슬라이드 시계  (0) 2012.06.13
조작하려는 엘리먼트 선택하기  (0) 2012.06.07
버튼이벤트->레이어 새창으로 표현  (0) 2012.05.08
list 추출및 select 구현  (0) 2012.05.08
Posted by 사라링
심원도
E-mail:wideeye@www.plasticsoftware.com
플라스틱 소프트웨어
Homepage:www.plasticsoftware.com


앞회에서 UML이 무엇이며 UML이 어떻게 만들어졌는지 대략적으로 알아보았다. 이번 호에서는 UML의 전반적인 구성에 대해서 알아보도록 하겠다.
1. UML과 방법론의 차이
UML의 구성을 알아보기에 앞서 먼저 UML과 방법론의 차이를 알아야 한다. 필자는 UML을 공부하는 초기에 UML을 하나의 방법론으로 착각하는 오류를 하였다. 물론 똑똑한 독자는 이러한 오류를 범하지 않으리라 생각하지만 혹시나 하는 마음에 먼저 언급하려고 한다.
방법론이란 말그대로 어떠한 작업을 할 때 이러저러한 절차를 가지고 작업을 하면 된다라고 하는 것을 이론적으로 정립을 하여놓은 것이다. 소프트웨어공학에서 많은 방법론이 있어왔고 현재도 수많은 방법론이 존재한다. 사실 프로그램을 하는 모든 사람은 나름대로의 방법론을 가지고 있다. 그러한 나름의 방법론이 작업을 얼마만큼 효과적으로 만드는지에 따라 좋은 방법론인지 아닌지 결정 날 것이다.
그럼 UML은 무엇인가?  UML은 이러한 방법론을 적용할 때의 결과물을 나타내기 위한 도구이다.  예를 들면 모든 소프트웨어를 설계 할 때 어떠한 표준적인 규칙을 가지고 설계도를 그려야한다. 이때 설계의 표준이 되는 것이 UML이다.  건축도면에서 나오는 건물 내부의 여러가지 표준적인 표기라 보면 될 것이다.  즉 각자 다양한 방법론을 자기의 프로젝트에 적용하더라도 UML을 공통적으로 적용할 수 있다.
2. UML의 구성
이제 UML이 어떻게 구성되어있는지 알아보도록 하겠다.  전체 UML은 8가지 다이어그램으로 나타난다. 시스템의 정적인 면을 나타내는 클래스 다이어그램(Class Diagram)이 있고 동적인 면을 나타내는 콜레버레이션 다이어그램(Collaboration Diagram), 시퀸스 다이어그램(Sequence Diagram), 상태 다이어그램(Statechart Diagram), 액티비티 다이어그램(Activity Diagram), 디플로이먼트 다이어그램(Deployment Diagram), 컴포넌트 다이어그램(Component Diagram)으로 구성되어져 있다.
이외로 유스케이스 다이어그램(Usecase Diagram)이 존재한다. 유스케이스 다이어그램을 두 부류로 나누지 않은 이유는 다른 모든 다이어그램을 그리기 위해 기반이 되는 다이어그램이기 때문이다.이제 각 다이어그램이 시스템의 어떠한 면을 반영하는지 간단하게 알아보도록 하자.
(1) 유스케이스 다이어그램 (Usecase Diagram)
유스케이스 다이어그램은 유스케이스를 그려놓은 다이어그램이다. 여기서 유스케이스란 말 그대로 컴퓨터 시스템과 사용자가 상호작용을 하는 하나의 경우이다. 예를들어 보험처리 프로그램의 경우에 "고객이 보험증권에 sign한다.",  "보험 판매원이 판매통계량을 종합한다." 등이 use case가 된다. 이러한 유스케이스 다이어그램은 시스템 구축의 초기에 이 시스템이 어떠한 일을 하는지에 대한 부분을 사용자 입장에서 이해할 수 있을 정도로 기술을 하여야 한다. 이러한 유스케이스 다이어그램은 사용자와의 대화수단으로 그리고 앞으로 구축해 나갈 때의 밑바탕이 되는 것이다.
사용자 삽입 이미지

그림 1 - 유스케이스 다이어그램
(2) 클래스 다이어그램 (Class Diagram)
클래스 다이어그램의 경우 시스템 내부에 존재하는 클래스들을 선별하여 나타내고 각 클래스들의 속성(Attribute)과 행위(Behavior)를 기입한다. 여기서 클래스들 사이에 여러가지 관계(Relationship)를 가질수 있다. 예를 들어 연관관계(Association)은 클래스와 클래스가 어떠한 연관을 가지고 있음을 나타내고 여기서 세부적으로 복합연관(Composition)과 집합 연관관계 (Aggregation) 등으로 나뉘어 질 수 있다. 이외에 상속관계(Generalization), 의존관계(Dependency)가 나타날 수 있다. 클래스 다이어그램을 그리고자 할 때 항상 추상화 단계를 고려하여서 그리도록 하여야 할 것이다. 추상화의 단계가 높은 경우 대충의 속성과 행위를 기입하고 대충의 관계를 기입하여도 충분할 것이다. 이 단계에서 너무 상세한 내용을 찾고 기입하다 보면 클래스 다이어그램 내부에서 구현의 단계에서 이루어져야 할 일이 이루어지는 오류를 범하게 된다. 이러한 오류는 실제 구현 단계에서 커다란 위험의 요소를 내재하게 된다.
사용자 삽입 이미지

그림 2 - 클래스 다이어그램
(3) 시퀸스 다이어그램 (Sequence Diagram)
시퀸스 다이어그램은 콜레버레이션 다이어그램과 함께 시스템의 동적인 면을 나타내는 대표적인 다이어그램이다. 시스템이 실행시 생성되고 소멸되는 객체를 표기하고 객체들 사이에 주고 받는 메시지를 나타내게 된다. 콜레버레이션 다이어그램 또한 메시지의 흐름을 나타내지만 시퀸스 다이어그램 만의 특징이라면 횡축을 시간축으로 하여 시간의 흐름을 나타내어 메시지의 순서에 역점을 두고있다.
사용자 삽입 이미지

그림 3 - 시퀀스 다이어그램
(4) 콜레버레이션 다이어그램 (Collaboration Diagram)
콜레버레이션 다이어그램 또한 시퀸스 다이어그램과 함께 메시지의 흐름을 나타낸다. 하지만 콜레버레이션 다어그램은 객체와 객체들 사이의 관계 또한 표기하게 된다. 실제 UML에서 클래스의 인스턴스인 객체를 표기하는 다이어그램이 명시적으로 존재하지 않는다. 이러한 객체들 사이의 관계를 나타내기 위해 별도로 오브젝트 다이어그램(Object Diagram)을 사용하여도 되지만 오브젝트 다이어그램은 클래스 다이어그램과 크게 차이점이 없는 관계로 UML의 표준에는 포함되어있지 않다. 갑자기 이러한 오브젝트 다이어그램을 여기서 언급하는 이유는 객체들 사이의 관계를 표기하기 위해 클래스 다이어그램과 거의 동일한 오브젝트 다이어그램을 그리기 보다는 특별히 클래스 다이어그램과 차이점이 되는 부분을 여기 콜레버레이션 다이어그램에 기입하는 것이 좋을 것이다.
사용자 삽입 이미지

그림 4 - 콜레버레이션 다이어그램
(5) 상태 다이어그램 (Statechart Diagram)
상태 다이어그램은 한 객체의 상태 변화를 다이어그램으로 나타낸 것이다. 시스템의 실행시 객체의 상태는 메시지를 주고 받음으로써 또한 어떠한 이벤트를 받음으로써 많은 변화가 있을 수 있다.  실제 시스템에서 실행시 많은 객체가 생성되고 소멸된다. 이렇게 무수한 객체의 상태 전부를 모두 다이어그램으로 나타내는 것은 불가능하다.  결국 상태 다이어그램은 특별히 관심을 가져야 할 객체에 관하여 그리고 특정 조건에 만족하는 기간동안의 상태를 표시하여야 한다.
사용자 삽입 이미지

그림 5 - 상태 다이어그램
(6) 액티비티 다이어그램 (Activity Diagram)
액티비티 다이어그램은 플로우챠트가 UML에 접목이 되었다면 가장 이해가 빠를 것이다.  시스템 내부에 존재하는 여러가지 행위들 그리고 각 행위의 분기, 분기되는 조건 등을 모두 포함 하게 된다. 이러한 액티비티 다이어그램에서 기존 플로우 챠트와 다른 점은 어떠한 행위에 따라 객체의 상태를 표기할 수 있다는 것이다. 이러한 점을 제외하고 기존 플로우챠트와 표기법과 의미가 약간씩 달라질 뿐 크게 다르지 않다라고 보아도 좋다.
사용자 삽입 이미지

그림 6 - 액티비티 다이어그램
(7) 디플로이먼트 다이어그램 (Deployment Diagram) 과 컴포넌트 다이어그램 (Component Diagram)
이 두 다이어그램은 시스템의 물리적인 부분의 구성을 나타낸다. 디플로이먼트 다이어그램은 실제 하드웨어적인 배치와 연결상태를 나타낸다. 그리고 컴포넌트 다이어그램은 소프트웨어의 물리적 단위(Exe, dll 등 기타 library)의 구성과 연결상태를 나타내게 된다.
사용자 삽입 이미지

그림 7 - 디플로이먼트 다이어그램
사용자 삽입 이미지

그림 8 - 컴포넌트 다이어그램
3. 이외의 사항들
지금까지 UML의 다이어그램적인 구성에 대하여 알아보았다. 하지만 UML은 이러한 다이어그램적인 사항이 아닌 확장을 위한 여러가지 도구들을 준비되어있다. 예를들어 스테레오타입(Stereotype)이나 컨스트레인트(Constraint) 등의 의미적 변환을 위한 도구가 있다. 그리고 UML은 의미적인 무결성을 위해 메타모델을 위해 준비해 두었다. 이제 전체적인 UML의 구성이 어떻게 되어있는지 알수 있을 것이다.  다음 회부터 본격적으로 UML의 세부적 사항을 요목조목 알아보도록 하겠다.


Posted by 사라링

div 불투명 깔기 . 소스

2012. 6. 8. 18:19
<script type="text/javascript">
        // [ by Park. ] AlphaLayer Object Function
        alpha = new Object
        alpha = {
            clear  : function() { 
                        alpha.create().style.display = "none"
                        document.getElementsByTagName('HTML')[0].style.overflow = "";
                },
            apply  : function(co,op) {
                        var Alpha = alpha.create()
                        var alphacolor = co ? co : "#ffffff"
                        var opacity = op ? op : "50"
                        document.getElementsByTagName('HTML')[0].style.overflow = "hidden";
                        with (Alpha.style) {
                            width      = document.body.scrollWidth + "px";
                            height     = document.body.scrollHeight + "px";
                            background = alphacolor;
                            filter     = "alpha(opacity=" + opacity + ")";
                            opacity    = op / 100;
                            display    = "block";
                        }
                },
            create : function() {
                        if (!document.getElementById('alpha')) {
                            var alphaDiv = document.createElement('div');
                            alphaDiv.setAttribute('id', 'alpha');
                            with(alphaDiv.style) {
                                display  = "none";
                                position = "absolute";
                                top      = "0";
                                left     = "0";
                                zindex   = "90";
                            }
                            document.body.appendChild(alphaDiv)
                            window.onresize = alpha.resize
                        }
                        return document.getElementById('alpha')
                },
            resize : function() {
                        var Alpha = alpha.create()
                        with (Alpha.style) {
                            width      = document.body.scrollWidth + "px";
                            height     = document.body.scrollHeight + "px";
                        }
                }
        }
    </script>


사용방법
- 알파레이어 온    : alpha.apply('색상','투명도')  [ 색상 및 투명도 미지정시 디폴트는 흰색에 50% 입니다 예) alpha.apply() ]
- 알파레이어 오프  : alpha.clear()




+++ 추가

<html>

<head> 


<META HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=euc-kr"> 


<title>Layer Test</title>


<script language="JavaScript"> 


var newArticleDivId = "write_article_layer";

var newArticleUrl = "http://www.naver.com/";

var minimumMargine = 50;

var maximumWidth = 800;


/*

 * openLayeredDialog

 * 레이어에 떠 있는 iFrame을 웹 페이지에 표시한다.

 */

function openLayeredDialog() {

    // 배경이 되는 반투명 레이어를 생성한다.

    var div1 = document.createElement("DIV");

    div1.id = newArticleUrl;

    div1.onclick = function () {closeLayeredDialog(false);};

    div1.style.position = "absolute";

    div1.style.height = "100%";

    div1.style.width = "100%";

    div1.style.top = "0";

    div1.style.left = "0";

    div1.style.background = "#000000";

    div1.style.opacity = "0.6";

    div1.style.filter = "alpha(opacity=60)";

    

    // iFrame을 담는 레이어를 생성한다.

    var div2 = document.createElement("DIV");

    div2.id = newArticleDivId + "_inner";

    div2.style.position = "absolute";

    div2.style.background = "#ffffff";

    

    // iFrame을 생성한다.

    var iframe1 = document.createElement("IFRAME");

    iframe1.src = newArticleUrl;

    iframe1.frameborder = "0";

    iframe1.style.height = "100%";

    iframe1.style.width = "100%";

    

    // 앞서 생성한 Element들을 웹 페이지에 추가한다.

    div2.appendChild(iframe1);

    document.body.appendChild(div1);

    document.body.appendChild(div2);

    

    // 레이어의 크기를 조정한다.

    adjustmentLayeredDialog();

    

    // 웹브라우저의 크기를 조절할 때 발생하는 이벤트의 핸들러를 등록한다.

    window.onresize = function(event) {adjustmentLayeredDialog();};

}


/*

 * closeLayeredDialog

 * 레이어를 제거한다.

 * 인자 normalClose가 true라면 Confirm 대화 창을 표시한다.

 * 인자 normalClose가 false라면 Confirm 대화 창을 표시하지 않는다.

 */

function closeLayeredDialog(normalClose) {

    // Confirm 대화 창을 표시한다.

    if (!normalClose) {

        willClose = confirm("이 페이지에서 나가면 작성하던 내용들은 저장되지 않습니다.\n정말 나가겠습니까?");

    } else {

        willClose = true;

    }

    

    // 레이어를 제거한다.

    if (willClose) {

        var child_background = document.getElementById(newArticleDivId);

        var child_inner = document.getElementById(newArticleDivId + "_inner");

        

        if (child_background) {

            document.body.removeChild(child_background);

        }

        if (child_inner) {

            document.body.removeChild(child_inner);

        }

        

        // 레이어를 제거하며 웹브라우저의 크기를 조절할 때 발생하는 이벤트의 핸들러도 제거한다.

        window.onresize = null;

    }

}


/*

 * adjustmentLayeredDialog

 * 레이어를 크기와 위치를 조정한다.

 */

function adjustmentLayeredDialog() {

    var child_inner = document.getElementById(newArticleDivId + "_inner");

    if (child_inner) {

        var clientHeight = document.body.clientHeight;

        var clientWidth = document.body.clientWidth;

        var top = minimumMargine;
        var left = 0;

       

        var height = clientHeight - minimumMargine * 2;

        var width = clientWidth - minimumMargine * 2;

        

        if (width > maximumWidth) {

            width = maximumWidth;

        }

            

        left = (clientWidth - width) / 2;

    

        child_inner.style.height = height;

        child_inner.style.width = width;

        child_inner.style.top = top;

        child_inner.style.left = left;

    }

}


</script> 


</head> 


<body>


<a href="javascript:openLayeredDialog();">레이어 보이기</a>


</body>

</html>



'HTML5.0' 카테고리의 다른 글

windy 실시간 기상 영상  (0) 2019.10.09
HTML --> PDF 파일로 변환 하기 . 펌) 정윤재님 노트  (0) 2013.04.05
html animation  (0) 2012.06.08
div의 overflow 및 postion  (0) 2012.06.07
캔버스 위에 div 를 올리자.  (0) 2012.06.05
Posted by 사라링

html animation

2012. 6. 8. 16:05

oinc는 Firefox와 chrome에서 테스트 했습니다. IE에서는 테이블이 깨지거나 이미지가 보이지 않을 수 있습니다. 특히 구글 Docs이미지의 경우 엑박처리될 수 있습니다.

Contents

1 시작하기
2 몇가지 알아 둘 점
2.1 자바스크립트는 변수의 이름에 대,소문자 구별을 한다
2.2 자바스크립트는 브라우저안에서 1개의 쓰레드로 돌아간다
2.3 한 개의 function이 끝날때까지 화면에 적용 되지 않는다
2.4 자바스크립트에는 sleep() 이 없다
3 애니메이션을 구현하는 방법
3.1 몇가지 필터들
3.1.1 BlendTrans
3.1.2 RevealTrans
3.2 타이머를 이용한 애니메이션
3.2.1 setInterval
3.2.2 setTimeout
3.2.3 ClearTimeout
4 마치며


1 시작하기

  • 인터넷 브라우저에서 애니메이션을 구현하는 방법은 많다. flash를 이용하는 방법도 있고 HTML 기본 매크로를 이용하는 방법도 있다.
  • 이 문서에서는 IE(Netscape에서는 동작하지 않는다)에서 JavaScript(JS)를 이용해 애니메이션을 구현하는 방법을 다루고 있다.

2 몇가지 알아 둘 점


2.1 자바스크립트는 변수의 이름에 대,소문자 구별을 한다

  • joinc, Joinc, jOiNc 는 모두 다른 변수명이며 함수 이름으로 쓰일 때 역시 모두 다른 함수로 쓰인다.

2.2 자바스크립트는 브라우저안에서 1개의 쓰레드로 돌아간다

  • 이 부분은 처음 JS를 이용한 애니메이션을 구현했을 때 간과할 수 있는 부분이다.
  • JS는 브라우저 내에서 1개의 쓰레드가 잡스케쥴 되어 동작한다.
  • 1개의 트랜지션이 시피유를 독점한다면 다음 애니메이션은 보이지 않게 될 것이고, 한개의 애니메이션이 완벽하게 보인다고 해서 이를 간과한 설계를 한다면 동시에 여러개의 애니메이션이 이루어 질 때 낭패를 보게 될 것이다. (원하지 않은 위치로 이동, 떨림 현상 등)

2.3 한 개의 function이 끝날때까지 화면에 적용 되지 않는다

  • 예를 들어 레이어를 여러 개의 지점으로 이동시키는 함수가 있다고 하자. 이 함수를 실행시키면 화면에 빠르게 레이어가 이동 할 것이라고 예상한다. 하지만 자바스크립트에서 그 함수가 완전히 끝난 후에 return 이 떨어져야만 화면의 변화가 일어난다. (재귀적으로 자신을 호출해도 역시 결과는 같다.)
<script>
function move()
{
  var div=document.body.all["box"];
  div.style.left = "10px";
  div.style.top = "10px";
  div.style.left = "100px";
  div.style.top = "100px";
}
</script>
<body onload="move()">
<div id="box" style="position:absolute;border:1px solid black;width:100px;height:100px">상자~</div>
</body>
  • 위의 내용을 저장해서 브라우저로 보면 상자는 그냥 100, 100 의 위치로 이동한다. 절대 10, 10 으로 이동했다가 100, 100 으로 이동하지 않는다. 그럼 어떻게 해야 하는가! sleep()을 쓰면 될까? 아래를 보자..

2.4 자바스크립트에는 sleep() 이 없다

  • sleep()는 대부분의 언어(스크립트 포함)들이 지원하는 함수이다. 하지만 자바스크립트에는 없다. sleep() 이라는건 설정된 시간동안 잠잔다는걸 의미한다. 위에서 얘기한대로 자바스크립트는 1개의 단일 쓰레드에서 동작한다. 1개의 function이 sleep() 한다고 해도 기다려 줄 수가 없는 것이다.
  • 편법이 있지 않을까? 하는 사람이 있을 것이다. 본인이 이미 해봤다. 아래를 보자 -_-;
<script>
function plzplzplzplz_sleep()
{
  //자바애플릿의 thread.sleep()를 호출
}
</script>
자바애플릿 자바스크립트
thread.sleep(); |
  • plzplzplzplz_sleep()를 호출하면 sleep()과 같은 효과를 낼 수 있을까? 정답은 있다! 이다.
  • 타이머가 생겼다. 뭘 할 수 있을까? 혹시 plzplzplzplz_sleep() 에서 자바애플릿의 타이머를 호출하기 전과 후에 레이어의 위치를 이동시키면 애니메이션이 일어나지 않을까? 이번엔 NO 이다. 아까 말했듯이 한 개의 function이 완전히 완료 되야만 화면에 반영된다. 결론적으로 타이머가 있다고 해서 할 수 없었던 걸 할 수 있게 된 건 아니다.

3 애니메이션을 구현하는 방법

3.1 몇가지 필터들

  • CSS에는 filter 라는 property가 있다. 대부분의 DOM 오브젝트 들에는 filters 라는 객체가 있다. 이것들 중에서 자연스럽게 애니메이션을 구현 할 수 있는 필터들이 있다. (사실 이들은 transition들 이다.)
  • 일단 아래의 필터들을 한번 보자.

3.1.1 BlendTrans

<script>
function transition()
{
  document.all["transition_div"].style.filter="blendTrans(duration=1)";
  document.all["transition_div"].filters.blendTrans.Stop();
  document.all["transition_div"].filters.blendTrans.Apply();
  document.all["transition_div"].style.backgroundColor="black";
  document.all["transition_div"].filters.blendTrans.Play();
}
</script>
<div id="transition_div" onmouseover="transition()" style="width:100px;height:100px">마우스를 올려놓으면 배경색이 바뀐다.</div>

3.1.2 RevealTrans

<script>
function transition()
{
        document.all["transition_div"].style.filter="revealTrans(duration=1,transition=23)";
        document.all["transition_div"].filters.revealTrans.Stop();
        document.all["transition_div"].filters.revealTrans.Apply();
        document.all["transition_div"].style.backgroundColor="black";
        document.all["transition_div"].filters.revealTrans.Play();
}
</script>
<div id="transition_div" onmouseover="transition()" style="width:100px;height:100px">마우스를 올려놓으면 배경색이 바뀐다.</div>

  • blendTrans 는 서서히 오버레이 되듯 변화하고 revealTrans 는 transition 이라는 property의 값에 따라 변하는 모양이 다르다. 23은 랜덤한 모양으로 변화한다. transition 의 값들은 이 링크를 참고.
  • http://msdn.microsoft.com/workshop/author/filter/filters.asp
  • 둘다 지켜줘야 한다면 filters.FILTERNAME.Apply() 와 Play() 사이에 변화가 일어날 조건들을 넣어줘야 한다는 것이다. Stop()를 Apply() 전에 써준 것은 혹시나 이전에 애니메이션이 일어나고 있다면 멈추게 하려고 넣은 것이다. (사실 보다 안전한 방법이 있다. 애니메이션이 play 되고 있는지 아닌지를 판별하여 플레이 되고 있다면 멈추게도 할 수 있다. 각 필터마다 status 라는 property가 있다.)

3.2 타이머를 이용한 애니메이션

  • 올것이 왔다...

3.2.1 setInterval

  • 이 함수의 원형이다. vCode에는 실행시킬 다른 함수, iMilliSeconds는 int형의 밀리초 단위의 시간을 넣어준다. 리턴되는 값은 자바스크립트 내부에서 알고 있는 이 타이머의 ID 이다.
''iTimerID'' = window.'''setInterval'''(''vCode'',''iMilliSeconds'' '''[''', ''sLanguage''''']''')

예제
<script>
var i=0;
function plus()
{
        i++;
        document.body.innerText=i;
}
setInterval("plus()",1000);
</script>
<body></body>
  • 이 놈이 하는 일은 iMilliSeconds 만큼의 시간마다 vCode를 호출 하는 것이다. 위의 예제는 애니메이션이 아니던가?

예제
<script>
function move()
{
        document.body.all[0].style.top=document.body.all[0].offsetTop+1;
}
</script>
<body onload="setInterval('move()',100)">
<div style="position:absolute;border:1px solid black;top:1px">점점 커진다!!!!!</div>
</body>
  • 속았죠? 무슨 말인지는 실행을.. 이번엔 상식적으로 이해가 가는 애니메이션 이었다.

3.2.2 setTimeout

''iTimerID'' = window.'''setTimeout'''(''vCode'',''iMilliSeconds'' '''[''', ''sLanguage''''']''')
  • 위의 setInterval()과 똑같다! 그럼 뭐가 다른거지?
  • setInterval()은 한번 호출되면 브라우저가 종료되거나 Timer가 클리어 되기 전까지 계속 설정된 시간마다 vCode를 호출한다. 결론부터 말하면 setInterval()은 글자나 레이어를 깜빡이는 식의 단순한 동작에나 가끔 쓰인다. setTimeout()은 설정된 시간후에 vCode를 한번 실행 시킨다. 자바스크립트에서의 에니메이션에서 가장 중요한 눔이 바로 setTimeout() 이다!!!
  • 주의) setTimeout은 IE의 특정 버전에서 메모리릭 버그가 있다. 뉴스그룹을 뒤져보시라
  • 흠흠 왜 중요하냐면 애니메이션은 항상 일어나는게 아니라 특정한 동작이 있을때만 일어나고 의도하는만큼 움직이고 멈춰서야 하기 때문이다. setTimeout()은 단발성이므로 애니메이션의 한프레임 단위의 컨트롤이 가능하다.

예제
<script>
function move()
{
        document.body.all[0].style.top=document.body.all[0].offsetTop+1;
}
</script>
<body onload="setTimeout('move()',100)">
<div style="position:absolute;border:1px solid black;top:1px">점점 커진다!!!!!</div>
</body>
  • 위의 코드를 실행하면 처음에 한번 움찔 하고 말 것이다. setInterval()과 동일한 효과를 주려면 어떻게 해야 할까?

예제
<script>
function move()
{
        document.body.all[0].style.top=document.body.all[0].offsetTop+1;
        setTimeout('move()',100);
}
</script>
  • 똑같이 움직이는가? 이 문서를 잘! 읽은 사람이라면 질문을 할 것이다. 한 개의 function 내에서는 동작이 끝나야 화면에 적용된다는건 어디로 가버린거냐! 흥분하지 말고 아래를 보자
move() 실행
레이어를 아래로 1 픽셀 이동한다
100ms 후에 move() 호출 예약
move() 종료, 화면 반영

100ms 후, move() 실행

레이어를 아래로 1 픽셀 이동한다

100ms 후에 move() 호출 예약

move() 종료, 화면 반영
  • 이것의 반복이다.. setTimeout을 호출하고 function 는 종료 되는 것이다.. 당연히 화면에 반영된다.

예제: 100픽셀만 아래로 내리기
<script>
function move()
{
        if (document.body.all[0].offsetTop >= 100) return;
        document.body.all[0].style.top=document.body.all[0].offsetTop+1;
        setTimeout('move()',100);
}
</script>
  • 단 한줄이 추가되었다.
if (document.body.all[0].offsetTop >= 100) return;
  • 레이어의 위치가 위에서 100 픽셀이라면 move() 함수가 바로 return 되버린다. 당연히 return 아래에 있는 setTimeout()은 호출되지 않고 애니메이션은 중지된다. 이를 이용한 무수한 조합은 DIY!

3.2.3 ClearTimeout

  • 중요하다! 위의 setTimeout() 으로 아무리 컨트롤을 잘 한다고 해도 예외는 항상 존재한다!!

예제
<script>
function move()
{
        //레이어를 1픽셀씩 20까지 아래로 이동한다.
        if (document.body.all[0].offsetTop == 20) return;
        document.body.all[0].style.top=document.body.all[0].offsetTop+1;
        setTimeout('move()',100);
}
function move2()
{
        //레이어를 화면 맨 위로 이동한다.
        if (document.body.all[0].offsetTop == 0) return;
        document.body.all[0].style.top=document.body.all[0].offsetTop-1;
        setTimeout('move2()',100);
}
</script>
<body onload="setTimeout('move()',50); setTimeout('move2()',100);">
<div style="position:absolute;border:1px solid black;top:10px">점점 커진다!!!!!</div>
</body>
  • 어떤가! -_-; 덜덜덜 떨고 있는 레이어가 보이시는가. 이 예제는 극적인 상황을 억지로 연출한 것이지만 실제로 이렇게 의도하지 않은 상황이 벌어질 수 있다. move()와 move2()가 서로 자신이 원하는 위치로 레이어를 움직이려고 힘을 쓰는 것이다. 아래의 예제에서는 950ms 후에 move2의 타이머를 클리어 해버림으로써 950ms 후에는 정상적으로 애니메이션된다.

예제
<script>
var timer1, timer2;
function move()
{
        if (document.body.all[0].offsetTop == 20) return;
        document.body.all[0].style.top=document.body.all[0].offsetTop+1;
        timer1=setTimeout('move()',100);
}
function move2()
{
        if (document.body.all[0].offsetTop == 0) return;
        document.body.all[0].style.top=document.body.all[0].offsetTop-1;
        timer2=setTimeout('move2()',100);
}
function kill_move()
{
        clearTimeout(timer2);
}
</script>
<body onload="setTimeout('move()',50); setTimeout('move2()',100); setTimeout('kill_move()',950); ">
<div style="position:absolute;border:1px solid black;top:10px">점점 커진다!!!!!</div>
</body>
  • 저게 뭔소린가 하는 사람은 아래를 보라. (그리기 정말 귀찮다 ㅠ_ㅠ)

50ms timer1 = move()

100ms
timer2 = move2()
150ms timer1 = move()

200ms
timer2 = move2()
250ms timer1 = move()

300ms
timer2 = move2()
350ms timer1 = move()

400ms
timer2 = move2()
450ms timer1 = move()

500ms
timer2 = move2()
550ms timer1 = move()

600ms
timer2 = move2()
650ms timer1 = move()

700ms
timer2 = move2()
750ms timer1 = move()

800ms
timer2 = move2()
850ms timer1 = move()

900ms
timer2 = move2()
950ms timer1 = move()
timer2를 clearTimeout으로 해제
1000ms

move2()는 앞으로 실행되지 않는다
1050ms timer1 = move()


  • 간단히 얘기하면 setTimeout 은 앞으로 몇ms 후에 어떤 작업을 하라고 예약하는 것이고 clearTimeout은 예약된 작업이 깨어나기 전에 작업 자체를 없애버리는 것이다.

4 마치며

  • 실제 JS를 이용한 개발 작업 중에는 위의 예제들 보다 많은 예외 상황을 고려해야 하며 예기치 못한 문제가 어디서 나올지 모른다. 몇가지 특성만을 잘 파악한다면 원하는 효과들을 구현하는데 문제가 없을 것이다.

출처 : http://www.joinc.co.kr/modules/moniwiki/wiki.php/JavaScript%B8%A6%20%C0%CC%BF%EB%C7%D1%20%BE%D6%B4%CF%B8%DE%C0%CC%BC%C7#s-2.2


'HTML5.0' 카테고리의 다른 글

HTML --> PDF 파일로 변환 하기 . 펌) 정윤재님 노트  (0) 2013.04.05
div 불투명 깔기 . 소스  (0) 2012.06.08
div의 overflow 및 postion  (0) 2012.06.07
캔버스 위에 div 를 올리자.  (0) 2012.06.05
canvas source  (0) 2012.06.05
Posted by 사라링

prepareStatement 이나 statement 를 사용할 경우 desc 는 사용이 안된다.

기것은 desc 명령이 오라클 쿼리 문이 아닌 sqlPlus 의 명령어이기 때문이다.

따라서 명령어의 경우

SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, NULLABLE FROM USER_TAB_COLUMNS WHERE TABLE_NAME='tablename' ORDER BY COLUMN_ID;


이며

preparestatement 의 경우

이경우  'tablename'를 ? 으로 바꾸어 


SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, NULLABLE FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? ORDER BY COLUMN_ID;


psmt.setString(1,테이블매개변수);

로 셋팅 하면 된다.

'오라클' 카테고리의 다른 글

OUT Join  (0) 2012.08.08
SYS_CONNECT_BY_PATH  (0) 2012.07.26
오라클연습  (0) 2012.05.08
sqlplus에서 셀렉트 update문 가져 오기.  (0) 2012.05.08
OCP정리  (0) 2012.05.08
Posted by 사라링

div의 overflow 및 postion

2012. 6. 7. 18:33

div 태그에서 스크롤을 사용하기 위헤서는 overflow속성을 이용한다.

2D인 화면에서 스크롤은 x, y 축으로 발생할수 있는데, 각각을 따로 설정하기 위해서는 overflow-x, overflow-y를 사용하고, 둘다 한꺼번테 컨트롤 하기 위해서는 overflow만을 사용한다.

 

속성값은 항상 보이기 위해서는 scroll, div영역이 해당 설정영역을 넘어갈때 자동으로 스크롤을 보이게 하기 위해서는 auto를 값으로 사용한다. 또한, 스크롤을 숨기기위해서는 hidden을 사용하면 된다.

 

 

 

몇가를 예를 보자.

1. 가로 600px 이상이 되면 스크롤이 생김, 스크롤은 600이 넘지 않아도 보임

<div style="width:600px; overflow-x:scroll></div>

 

2. 가로 600px 이상이 되면 스크롤이 자동으로 생김. 가로 600이 넘지 않으면 스크롤은 보이지 않음

<div style="width:600px; overflow-x:auto></div>

 

3. 조금 복잡하게 사용해 보자.

스크롤을 자동으로 생기도록 하는데, 세로 스크롤이 처음부터 생기는것을 패딩해 주고, overflow-y=hidden으로 세로 스크롤을 강제로 보이지 않도록 하면된다.

<div style="width:600px; overflow:auto; overflow-y:hidden; height:auto; padding:0 0 17px 0;">

 


오랫만에 html / css 글을 작성합니다.
오늘은 css의 속성인 포지션 (position) 에 대해 포스팅해 보겠습니다.

사용된 이미지를 클릭하시면 조금은 크게 보실 수 있습니다.

일단 포지션(position) 을 이용한 예를 정리해 보겠습니다.

1. 포지션(position)을 이용한 예

다음 뷰 position:absolute;

다음뷰에서 볼 수 있는 화면입니다.
해당 제목에 마우스 오버를 하게 되면 간략한 내용의 박스가 나타나는 형태입니다.
이것도 포지션 (position)을 이용한 방법입니다.

지마켓 홈페이지 position:absolute;

홈페이지에서 많이 사용되는 퀵메뉴 or 윙메뉴 입니다.
홈페이지의 스크롤에 따라다니는 메뉴바 형태입니다.
이런 형태 또한 포지션(position) 을 이용해 위치를 고정시키고, 자바스크립트를 이용해 스크롤을 따라다는 모양으로 만들어 줍니다.

배너 position:absolute;

故노무현 전 대통령 서거 당시 블로그에 많이 보였던 배너 형태입니다.
이렇게 브라우져의 한 부분으로 위치시킬 경우에도 포지션(position)을 사용합니다.

2. 포지션 (position) 이란?
포지션 (position)은 요소의 위치를 설정할때 사용합니다.
위의 예처럼, 자신이 원하는 위치에 설정할 수 있습니다.

포지션 (position)의 속성 값에는 absolute, relative, fixed, static, inherit  총 5가지가 있습니다.
그리고 위치 설정을 하기 위해서는 top, left, bottom, right 의 스타일을 추가해주면 됩니다.
예) position:absolute, top:20px; left:20px;  절대적인 위치로 위로부터 20px 왼쪽으로부터 20px 떨어진 위치에 고정됩니다.

static - 포지션의 기본값으로 위치 설정을 해줄 수 있습니다.
absolute - 절대위치
relative - 상대위치
fixed - 위치를 고정시킵니다. 브라우져의 스크롤을 이동해도 정해진 위치에 고정시킵니다.
inherit  - 부모의 속성을 상속시켜줍니다.

지금까지는 사전적인 의미입니다.

3. 포지션 (position) 예제
가장 많이 이용하는 absolute, relative, fixed 를 예제로 보여드리겠습니다.

포지션 (position)의 속성이 relative 일 경우에는 현재 위치에서의 상대적인 위치에 이동을 합니다.

포지션 (position)의 속성이 absolute 일 경우에는 두가지 형태로 나뉘게 됩니다.
absolute 된 엘리먼트의 상위 엘리먼트의 속성이 relative 인것과 아닌것으로 나뉩니다.
아닐 경우에는, 브라우져 (body) 를 기준으로 절대적인 위치를 가지게 되고,
상위 엘리먼트의 속성이 relative 일 경우에는 상위 엘리먼트를 기준으로 절대적인 위치로 이동합니다.


포 지션 (position)의 속성인 fixed는 이미지에서 보는거와 같이 스크롤이 이동해도 항상 자신의 위치에서 이동이 없습니다. fixed 의 기준점은 브라우져 (body) 입니다. 그러므로, 브라우져의 스크롤을 이동하여도 브라우져가 기준점이기 때문에 이동하지 않습니다.

1.포지션(position)의 예에서도 보듯이, absolute의 속성을 많이 이용합니다.
relative는 주로, absolute 된 엘리먼트의 기준점으로 사용하기 위해 이용합니다.


'HTML5.0' 카테고리의 다른 글

div 불투명 깔기 . 소스  (0) 2012.06.08
html animation  (0) 2012.06.08
캔버스 위에 div 를 올리자.  (0) 2012.06.05
canvas source  (0) 2012.06.05
HTML 5.0 구조 및 FORM image  (0) 2012.06.04
Posted by 사라링

조작하려는 엘리먼트 선택하기

jQuery 2011/06/20 11:23

조작하려는 엘리먼트 선택하기

전 장에서도 간단히 살펴보았지만 우선 jQuery매소드를 사용하기 위해선 페이지에서 조작할 엘리먼트를 선택해야 한다. 여기선 이런 엘리먼트를 선택하는 방법에 대해 알아보자.
  • 기본 CSS 선택자를 이용해 선택하기
  • 위치로 선택하기
  • jQuery 정의 선택자로 선택하기
위의 세가지 방법을 이용해 엘리먼트를 선택하는 것에 대해 알아보자.

기본 CSS 선택자 사용하기

CSS를 사용해 본 유저라면 이 선택 기법은 익숙할 것이다.엘리먼트의 ID, CSS 클래스명, 태그명, 페이지 엘리먼트의 DOM 계층 구조를 이용해 엘리먼트를 선택하는 기법이 그것들이며 아래의 예를 보자.
  • a - 모든 링크 엘리먼트와 일치하는 선택자
  • #specialID - specialID를 아이디로 가지는 엘리먼트와 일치하는 선택자
  • .specialClass - specialClass를 클래스로 가지는 모든 엘리먼트와 일치하는 선택자
  • a#specialID.specialClass - 아이디가 specialID이고 specialClass를 클래스로 가지는 링크와 일치하는 선택자
  • p a.specialClass - 단락 엘리먼트 내에 선언되고 specialClass를 클래스로 가지는 모든 링크와 일치하는 선택자
이러한 기존의 CSS 선택자를 이용하여 엘리먼트를 선택할 수 있게 되는데, jQuery가 지원하는 선택자들은 아래와 같다.
선택자내 용
*모든 엘리먼트
E태그명이 E인 모든 엘리먼트
E FE의 자손이면서 태그명이 F인 모든 엘리먼트
E>FE의 바로 아래 자식이면서 태그명이 F인 모든 엘리먼트
E+FE의 형제 엘리먼트로 바로 다음에 나오는 엘리먼트 F
E~FE의 형제 엘리먼트로 다음에 나오는 모든 엘리먼트 F
E:has(F)태그명이 F인 자손을 하나 이상 가지는 태그명이 E인 모든 엘리먼트
E.C클래스명 C를 가지는 모든 엘리먼트 E
E#I아이디가 I인 엘리먼트 E
E[A]속성 A를 가지는 모든 엘리먼트 E
E[A=V]값이 V인 속성 A를 가지는 모든 엘리먼트 E
E[A^=V]값이 V로 시작하는 속성 A를 가지는 모든 엘리먼트 E
E[A$=V]값이 V로 끝나는 속성 A를 가지는 모든 엘리먼트 E
E[A*=V]값이 V를 포함하는 속성 A를 가지는 모든 엘리먼트 E
위의 선택자를 활용하는 방법에 대해 예제를 통해 알아보자.(예제보기)

위치로 선택하기

때로는 페이지에 있는 엘리먼트 위치나 다른 엘리먼트와 연관된 관계를 기반으로 엘리먼트를 선택해야 한다. 예를 들어 페이지에서 첫 번째 링크나 홀수 및 짝수 번째 문단 등을 선택하는 기법이 필요할 때가 있다. 이에 대해 정리한 것이 아래의 표이다.
선택자설 명
:first페이지에서 처음으로 일치하는 엘리먼트
:last페이제에서 마지막으로 일치하는 엘리먼트
:first-child첫 번째 자식 엘리먼트
:last-child마지막 자식 엘리먼트
:only-child형제가 없는 모든 엘리먼트를 반환
:nth-child(n)n번째 자식 엘리먼트
:nth-child(even|odd)짝수 혹은 홀수 자식 엘리먼트
:nth-child(Xn+Y)전달된 공식에 따른 n번째 자식 엘리먼트
:even / :odd페이지 전체의 짝수/홀수 엘리먼트
:eq(n)n번째로 일치하는 엘리먼트
:gt(n)n번째 엘리먼트 이후의 엘리먼트와 일치
:lt(n)n번째 엘리먼트 이전의 엘리먼트와 일치

jQuery 정의 선택자 사용하기

CSS 선택자를 이용해 우리는 원하는 DOM 엘리먼트를 선택할 수 있었지만 때로는 이것만으로 표현할 수 없는 특성이 있는 엘리먼트를 선택해야 한다. 예를 들어 라디어 버튼 중 check가 된 엘리먼트만을 선택하기에는 CSS선택자만으로는 부족하다. 이렇듯 부족한 부분을 jQuery 정의 선택자를 이용하여 채울 수 있다.
선택자설 명
:animated현재 애니메이션이 적용되고 있는 엘리먼트
:button모든 버튼을 선택
:checkbox체크박스 엘리먼트 선택
:checked선택된 체크박스나 라디오 버튼을 선택
:contains(foo)텍스트 foo를 포함하는 엘리먼트 선택
:disabled인터페이스에서 비활성화 상태인 모든 폼 엘리먼트를 선택
:enabled인터페이스에서 활성화 상태인 모든 폼 엘리먼트를 선택
:file모든 파일 엘리먼트를 선택
:header헤더 엘리먼트 선택
:hidden감춰진 엘리먼트 선택
:image폼 이미지를 선택
:input폼 엘리먼트만 선택
:not(filter)필터의 값을 반대로 변경
:parent빈 엘리먼트를 제외하고, 텍스트도 포함해서 자식 엘리먼트를 가지는 엘리먼트
:password패스워드 엘리먼트 선택
:radio라디오 버튼 엘리먼트 선택
:reset리셋 버튼을 선택
:selected선택된 엘리먼트 선택
:submit전송 버튼을 선택
:text텍스트 엘리먼트 선택
:visible보이는 엘리먼트 선택
여러 jQuery 정의 선택자가 폼과 관련되며 덕분에 특정 엘리먼트의 타입이나 상태를 세련되게 표현할 수 있다. 선택자 필터도 조합할 수 있다. 예를 들어 활성화 되고 선택된 체크박스만 일치시키려 한다면 다음과 같다.
 
 
:checkbox:checked:enabled

새로운 HTML 생성하기

jQuery() 함수는 페이지의 엘리먼트를 선택할 뿐 아니라 새로운 HTML을 생성할 수도 있다.
 
$("<div>안녕</div>")
이 표현식은 페이지에 추가할 새로운 <div> 엘리먼트를 생성한다. 다음의 코드를 이용하여 <div> 엘리먼트를 두 개 생성해보자.
 

$("<div class='foo'>내가 foo를 가졌다.</div><div>나는 foo를 가지지 않았다.")

.filter(".foo").click(function(){ alert("내가 foo이다."); })

.end().appendTo("#someParentDiv");

위의 코드는 <div> 엘리먼트를 생성하는데 첫번째 <div> 엘리먼트는 foo 클래스가 있고, 다른 하나에는 없다. 생성한 첫번째 <div> 엘리먼트를 클릭하면 alert()가 실행된다. 마지막으로 end()메서드를 이용해 필터링 이전의 두 <div>엘리먼트를 지닌 집합으로 돌아간 뒤, 이 집합을 id가 someParentDiv인 엘리먼트에 덧붙인다.


'J-Query' 카테고리의 다른 글

슬라이드 시계  (0) 2012.06.13
JQuery 시계  (0) 2012.06.13
버튼이벤트->레이어 새창으로 표현  (0) 2012.05.08
list 추출및 select 구현  (0) 2012.05.08
9일차 XML문서  (0) 2012.05.08
Posted by 사라링

Now it’s time to show how to crate a canvas that “overlays” your web-page. By overlay, we mean “on-top-of” or “positioned above your web page.  There are several ways to do this. One is to create the and position it above every other elements in the page.

The technique presented here creates the canvas programatically and puts it as the first element of the html body. The benefit of this approach is that you can “embed” the same code on different pages, with only minimal changes.

Creating And Appending Canvas Into Html

In the code below, we are creating a ‘canvas’ element programatically and then appending it into the of the html page.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
<script type="text/Javascript">
 function createCanvasOverlay()
 {
  myCanvas = document.createElement('canvas');
  document.body.appendChild(myCanvas);
  myCanvas.style.position = 'absolute';
  myCanvas.style.left="0px";
  myCanvas.style.top="0px";
  myCanvas.style.zIndex="100";
  myCanvas.style.width="100%";
  myCanvas.style.height="100%";
  myCanvas.width=myCanvas.offsetWidth;
  myCanvas.height=myCanvas.offsetHeight;
}
</script>

The code seems to make sense. However, if you run it, you will end up with a canvas with a dimensions of (0,0). It is because the canvas width and height (not the same as style.width and style.height) does not take percentage values, and we’re forcing them to take 100% values. What can be done about this? We can try appending the canvas into a div element instead.

Creating And Appending Canvas Into A DIV And Then Into Html

In the modified code below, we first create a div element, and then we add the canvas as the child of the div.


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script type="text/Javascript">
 function createCanvasOverlay()
 {
   // Create a blank div where we are going to put the canvas into.
    var canvasContainer = document.createElement('div');
   // Add the div into the document
    document.body.appendChild(canvasContainer);
    canvasContainer.style.position="absolute";
    // Set to 100% so that it will have the dimensions of the document
    canvasContainer.style.left="0px";
    canvasContainer.style.top="0px";
    canvasContainer.style.width="100%";
    canvasContainer.style.height="100%";
    // Set to high index so that this is always above everything else
    // (might need to be increased if you have other element at higher index)
    canvasContainer.style.zIndex="1000";
 
    // Now we create the canvas
    myCanvas = document.createElement('canvas');
    myCanvas.style.width = canvasContainer.scrollWidth+"px";
    myCanvas.style.height = canvasContainer.scrollHeight+"px";
    // You must set this otherwise the canvas will be streethed to fit the container
    myCanvas.width=canvasContainer.scrollWidth;
    myCanvas.height=canvasContainer.scrollHeight;
    myCanvas.style.overflow = 'visible';
    myCanvas.style.position = 'absolute';
    // Add int into the container
    canvasContainer.appendChild(myCanvas);
 }
</script>


The code created a canvasContainer div which we will embed the canvas into. To get the dimensions of the page, we need to embed canvasContainer into the body of the html. It needs to have absolute positioning and be above any other elements in the html, so we set the zIndex to 1000 (if your page has lots of elements, you may need to increase the zIndex.

Why this works is because canvasContainer does have pixel values (as opposed to percentage). You must remember to add the container into the document first, with 100% and 100% as the style.width and style.height. We then overlaid the canvas into the div. Another thing to pay attention is there should be no space in document.body.scrollWidth+”px”; and containerDiv.scrollHeight+”px”;. We’re using scrollWidth and scrollHeight so that if the page is larger than the window, the canvas will cover the whole page, not just the visible portion of the page.

If we want to create a canvas that fits into a particular existing element on your page, we can modify the code to take a canvasContainer as a parameter. This is shown below, where we can specify a div as the canvasContainer; if no canvasContainer is specified, the canvas will cover the whole html page.


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<script type="text/Javascript">
function createCanvasOverlay(color, canvasContainer)
 {
    if (!myCanvas)
    {
      // Append to body of the html if no container is specified
      if (!canvasContainer)
      {
        canvasContainer = document.createElement('div');
        document.body.appendChild(canvasContainer);
        canvasContainer.style.position="absolute";
        canvasContainer.style.left="0px";
        canvasContainer.style.top="0px";
        canvasContainer.style.width="100%";
        canvasContainer.style.height="100%";
        canvasContainer.style.zIndex="100";
        superContainer=document.body;
      }
      else
        superContainer=canvasContainer;
 
      myCanvas = document.createElement('canvas');
      myCanvas.style.width = superContainer.scrollWidth+"px";
      myCanvas.style.height = superContainer.scrollHeight+"px";
      // You must set this otherwise the canvas will be streethed to fit the container
      myCanvas.width=superContainer.scrollWidth;
      myCanvas.height=superContainer.scrollHeight;
      myCanvas.style.overflow = 'visible';
      myCanvas.style.position = 'absolute';
 
      var context=myCanvas.getContext('2d');
      context.fillStyle = color;
      context.fillRect(0,0, myCanvas.width, myCanvas.height);
      canvasContainer.appendChild(myCanvas);
  }
}
</script>


'HTML5.0' 카테고리의 다른 글

html animation  (0) 2012.06.08
div의 overflow 및 postion  (0) 2012.06.07
canvas source  (0) 2012.06.05
HTML 5.0 구조 및 FORM image  (0) 2012.06.04
HTML 5 설명 글 중 (일본어를 구글로 강제 번역함 ㅠㅠ )  (0) 2012.06.04
Posted by 사라링

canvas source

2012. 6. 5. 16:32

Our bottom layer

This text is displayed if your browser does not support HTML5 Canvas.

function draw1() {
  ctx1.clearRect(0, 0, WIDTH, HEIGHT);
  ctx1.fillStyle = "#FAF7F8";
  ctx1.beginPath();
  ctx1.rect(0,0,WIDTH,HEIGHT);
  ctx1.closePath();
  ctx1.fill();
  ctx1.fillStyle = "#444444";
  ctx1.beginPath();
  ctx1.arc(x, y, 10, 0, Math.PI*2, true);
  ctx1.closePath();
  ctx1.fill();

  if (x + dx > WIDTH || x + dx < 0)
    dx = -dx;
  if (y + dy > HEIGHT || y + dy < 0)
    dy = -dy;

  x += dx;
  y += dy;
}

The code for this animation is fully explained here. Simple Animation in the HTML5 Canvas Element

Our middle layer

This text is displayed if your browser does not support HTML5 Canvas.

function draw2() {
  ctx2.clearRect(0, 0, WIDTH, HEIGHT);
  ctx2.drawImage(city, 0, 0); 
}

We are simply drawing city.png http://html5.litten.com/layers/city.png to the canvas. The sky in this image is transparent.

Our top layer

This text is displayed if your browser does not support HTML5 Canvas.

function draw3() {
  ctx3.clearRect(0, 0, WIDTH, HEIGHT);
  ctx3.fillStyle = "#444444";
  ctx3.save();
  ctx3.translate(200,200);
  ctx3.rotate(x/20); 
  ctx3.fillRect(-15, -15, 30, 30);  
  ctx3.restore();
}

Here we transform the canvas’s coordinate system and rotate the square based on the global variable x which is used in layer 1 also. For more information on transforms with save() and restore() go here Understanding save() and restore() for the Canvas Context

Now to stack them

We use CSS to set all the canvases to an absolute position of (0,0) inside our parent DIV tag.


    position:absolute;
    left:0px;
    top:0px;

We also use CSS to set the z-index of our canvases. The z-index property specifies the stack order of an element. Items with lower z-index values go behind items with higher z-index values.


Bottom layer
    canvas id="layer1" 
    style="z-index: 1;
    
Middle layer    
    canvas id="layer2" 
    style="z-index: 2;

Top Layer    
    canvas id="layer3" 
    style="z-index: 3;      

DEMO Here's our finished canvas with full source code.

Now it doesn't matter that a canvas can only have one 2d context because we can just make multiple canvases and stack them.

If you have a question that you do not want published as a public comment, then use my contact page.

Have fun with the code as that is the easiest way to learn.

5 Responses to “Using Multiple HTML5 Canvases as Layers”

DanApril 24th, 2011 at 1:46 pm

Do you know whether you can superimpose a canvas (or stack of canvases) over a Google Map and draw and animate stuff over the map? Thanks for the great writeup.

YAUJune 28th, 2011 at 2:22 am

hello james
i created a playing card game which uses multiple canvases.
in the game, each object has its own canvas.
i got the idea of using multiple canvases from this your blog post.
tank you!

ono
http://onohugou.sakura.ne.jp
*supported browsers: firefox4 and chrome10+


'HTML5.0' 카테고리의 다른 글

div의 overflow 및 postion  (0) 2012.06.07
캔버스 위에 div 를 올리자.  (0) 2012.06.05
HTML 5.0 구조 및 FORM image  (0) 2012.06.04
HTML 5 설명 글 중 (일본어를 구글로 강제 번역함 ㅠㅠ )  (0) 2012.06.04
adobe Edge  (0) 2012.06.04
Posted by 사라링

Window open() Method


Definition and Usage

The open() method opens a new browser window.

Syntax

window.open(URL,name,specs,replace)

Parameter Description
URL Optional. Specifies the URL of the page to open. If no URL is specified, a new window with about:blank is opened
name Optional. Specifies the target attribute or the name of the window. The following values are supported:
  • _blank - URL is loaded into a new window. This is default
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded
  • name - The name of the window
specs Optional. A comma-separated list of items. The following values are supported:

channelmode=yes|no|1|0 Whether or not to display the window in theater mode. Default is no. IE only
directories=yes|no|1|0 Whether or not to add directory buttons. Default is yes. IE only
fullscreen=yes|no|1|0 Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode. IE only
height=pixels The height of the window. Min. value is 100
left=pixels The left position of the window
location=yes|no|1|0 Whether or not to display the address field. Default is yes
menubar=yes|no|1|0 Whether or not to display the menu bar. Default is yes
resizable=yes|no|1|0 Whether or not the window is resizable. Default is yes
scrollbars=yes|no|1|0 Whether or not to display scroll bars. Default is yes
status=yes|no|1|0 Whether or not to add a status bar. Default is yes
titlebar=yes|no|1|0 Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. Default is yes
toolbar=yes|no|1|0 Whether or not to display the browser toolbar. Default is yes
top=pixels The top position of the window. IE only
width=pixels The width of the window. Min. value is 100

replace Optional.Specifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported:
  • true - URL replaces the current document in the history list
  • false - URL creates a new entry in the history list


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The open() method is supported in all major browsers.


Examples

Example 1

The following example opens www.w3schools.com in a new browser window:

<html>
<head>
<script type="text/javascript">
function open_win()
{
window.open("http://www.w3schools.com")
}
</script>
</head>
<body>

<input type="button" value="Open Window" onclick="open_win()" />

</body>
</html>

Try it yourself »

Example 2

The following example opens an about:blank page in a new browser window:

<html>
<body>

<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("<p>This is 'myWindow'</p>")
myWindow.focus()
</script>

</body>
</html>

Try it yourself »


'자바스크립트' 카테고리의 다른 글

순수 HTML typing 게임  (0) 2012.08.16
자바 스크립트를 이용 할때 꼭 한번 읽어야 할것  (0) 2012.06.20
물고기 소스  (0) 2012.06.15
document.createElement  (1) 2012.06.14
event.keyCode 사용 하기.  (0) 2012.06.13
Posted by 사라링

BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (303)
JSP (32)
J-Query (41)
디자인패턴 (1)
JAVA (24)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (11)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
웹스퀘어_ (0)
Total :
Today : Yesterday :