가젯 문서 검색
죄송합니다. 이 문서는 더 이상 최신 버전이 아닙니다. 가장 최근 업데이트된 문서를 보시려면 영어 버전을 참고로 해주십시오. 불편을 끼쳐드려 죄송합니다.

사용자 인터페이스 만들기

본 문서에서는 귀하의 가젯에 여러 개의 사용자 인터페이스 요소를 추가하는 방법에 대해 설명합니다.

목차

  1. 가젯 높이 조정
    1. 작동방식
    2. 동적 콘텐츠 만들기
    3. 인덱스를 기준으로 탭 조작
    4. 맞춤형 탭 표시
  2. 끌기
    1. 소스 및 대상 추가 및 제거
  3. MiniMessage
    1. 작동방식
    2. 다른 위치에서 메시지 작성
    3. DOM 메서드를 사용하여 메시지 작성
    4. 타이머 메시지 작성
    5. 정적 메시지 작성
    6. 맞춤형 MiniMessage 표시
  4. 그리드
    1. 작동방식
    2. 간단한 그리드 예
    3. 추가 정보

가젯 높이 조정

기본적으로 가젯 높이는 200픽셀입니다. <ModulePrefs> 속성 height="nn"를 사용하여 기본값보다 크거나 작은 정적 높이를 지정할 수 있습니다. 콘텐츠 높이로 인해 가젯의 지정된 높이를 초과하는 경우 <ModulePrefs> 속성 scrolling="true"를 사용하여 가젯에 세로 스크롤 막대를 표시할 수 있습니다.

하지만 일부 가젯에서는 해당 높이를 동적으로 변경할 수 있어야 합니다. 예를 들어, 목록 내용에 따라 높이를 늘리거나 줄여야 하는 목록 가젯이 있다고 가정합시다. 사용자가 목록에 항목을 추가하면 가젯이 확장됩니다. 목록을 지우면 가젯은 원래 높이로 돌아갑니다. 실행 중인 가젯은 다음과 같이 표시됩니다.

식료품 목록 가 

가젯이 자동으로 크기를 조정할 수 있게 하려면 가젯 사양에 다음 항목을 추가해야 합니다.

참고: 동적 높이 기능은 iGoogle에서만 작동하며 신디케이션이나 가젯이 다른 Google 사이트에 추가된 경우에는 작동하지 않습니다.

예를 들어, 다음은 식료품 목록 가젯에 대한 가젯 사양입니다.

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="My Grocery List" 
    height="100"> 
    <Require feature="dynamic-height"/>
  </ModulePrefs>
  <Content type="html">
  <![CDATA[
    <script type="text/javascript">
    // This example lets users add items to a grocery list and then clear the list.
    // When items are added or cleared, the gadget resizes itself.
    var mylist = "";
    var flag = 0;

    // Function that is invoked whenever user clicks the Add button to add an
    // item to the list.
    function addToList (form) {
        var input = _trim(form.inputbox.value);
        if (input == "") {
            return;
        }

        // Make alternating lines green/white, depending on value of flag variable.
        if(flag == 0){
            mylist += "<div style='padding-left: 5px;background-color: #E6FFE6; font-family:Arial, Helvetica;'>" +input + "</div>";
            flag = 1;
        }
        else {
            mylist += "<div style='padding-left: 5px;font-family:Arial, Helvetica;'>" +input + "</div>";
            flag = 0;
        }

        // Call setContent to output HTML to div and resize gadget
        setContent(mylist);
    }

    // Clear the list
    function clearList(form) {
        // Call setContent to remove all items from the list and resize the gadget
        setContent("");
    }

    // Outputs content to the div and resizes the gadget
    function setContent(html) {
        _gel('content_div').innerHTML = html;

       // Tells gadget to resize itself
       _IG_AdjustIFrameHeight();
    }
    </script>
  <FORM NAME="myform" ACTION="" METHOD="GET"><BR>
  <INPUT TYPE="text" NAME="inputbox" VALUE="">
  <INPUT TYPE="button" NAME="button" Value="Add" onClick="addToList(this.form)">
  <INPUT TYPE="button" NAME="button2" Value="Clear" onClick="clearList(this.form)">
  </FORM>
  <div id="content_div"></div>
  ]]>
  </Content>
</Module>

가젯의 너비 및 높이 테스트에 대한 도움말은 너비 및 높이 테스트를 참조하시기 바랍니다.

탭 라이브러리를 사용하여 가젯에 탭 사용자 인터페이스를 추가할 수 있습니다. 탭을 사용하려면 가젯 사양에 최소한 다음 항목을 포함해야 합니다.

일반적으로 사용자가 마지막으로 선택한 탭을 가젯에서 지속적으로 저장할 수 있도록 setprefs 라이브러리도 포함됩니다. 사용자가 마지막으로 선택한 탭을 가젯에서 기억해야 하는 경우가 종종 있습니다. 사용자가 iGoogle을 떠났다가 다시 돌아오는 경우 가젯에서 기억한 탭을 자동으로 로드합니다. 해당 기능을 사용하려면 가젯 사양 안에 다음 두 줄의 코드를 포함해야 합니다.

<Require feature="setprefs"/>
...
<UserPref name="selectedTab" datatype="hidden"/>

작동방식

각 탭에는 해당 <div>의 ID와 일치하는 고유한 ID가 있습니다. <div>는 탭의 콘텐츠가 있는 위치입니다. <div> 컨테이너를 사용자가 직접 제공하지 않으면 탭 라이브러리에서 컨테이너 하나를 생성합니다.

다음 중 하나의 방법으로 탭을 추가하고 해당 탭을 콘텐츠로 채울 수 있습니다.

방법 1: 탭을 생성할 때 탭 ID를 캡처하고 해당 ID를 사용하여 탭에 해당하는 <div>에 콘텐츠를 추가합니다.

var one_Id = tabs.addTab("One"); 
_gel(one_Id).innerHTML = "Content for tab One.";

방법 2: 탭을 생성하고 해당 <div>를 가젯의 HTML 부분에 추가합니다. 정적 콘텐츠는 <div>에 삽입합니다.

tabs.addTab("Two", "two_id");
...
</script>     
<div id="two_id" style="display:none">Content for tab Two.</div>

방법 3: 탭을 생성하고 해당 <div>를 가젯의 HTML 부분에 추가합니다. 정적 콘텐츠는 <div>에 삽입합니다. 콜백 함수를 사용하여 정적 콘텐츠에 동적 콘텐츠를 추가합니다.

tabs.addTab("Three", "three_id", callback); 
...
function callback(tabId) {
var p = document.createElement("p");
p.innerHTML = "This is dynamic content generated in callback.";
_gel(tabId).appendChild(p);
} ...
</script>
<div id="three_id" style="display:none">This is static content for tab Three.</div>

방법 4: addDynamicTab() 함수를 사용하여 이름순으로 탭을 추가하고 동적 콘텐츠를 생성할 수 있도록 콜백 함수를 제공합니다. 이 시나리오에서는 탭 라이브러리에서 <div>가 생성됩니다.

tabs.addDynamicTab("My_Tab", callback); 
...
function callback(tabId)
{
// do something
_gel(tabId).innerHTML = [something];
}

네 번째 방법인 콜백을 사용하여 동적 콘텐츠를 생성하는 방법에 대한 예를 보려면 동적 콘텐츠 생성을 참조하시기 바랍니다. 다음은 탭을 추가하고 해당 탭을 콘텐츠로 채우는 처음 3가지 방법이 포함된 샘플 가젯입니다.

가젯 사양은 다음과 같습니다.

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="Simple Tabs" height="140"> 
    <Require feature="tabs" /> 
  </ModulePrefs>
  <Content type="html">
  <![CDATA[ 

    <script type="text/javascript">
    function init() {
        // Initialize tabs, designate the tab named "Two" as
        // the tab selected by default.
        var tabs = new _IG_Tabs(__MODULE_ID__, "Two");

        // Technique #1: Capture the tab's ID when you create it, and use the ID 
// to add content to the tab's corresponding <div>. var one_Id = tabs.addTab("One");
_gel(one_Id).innerHTML = "Content for tab One."; // Technique #2: Create the tab and define a corresponding <div> in the
// HTML portion of the gadget. Add static content to the <div>. tabs.addTab("Two", "two_id"); // Technique #3: Create the tab and define a corresponding <div> in the
// HTML portion of the gadget. Add static content to the <div>.
// Use a callback function to add dynamic content to the static content. tabs.addTab("Three", "three_id", callback); } // Callback that adds dynamic content to the static content already // in tab Three. function callback(tabId) {
var p = document.createElement("p");
p.innerHTML = "This is dynamic content generated in callback.";
_gel(tabId).appendChild(p);
} // Call init function to initialize and display tabs. _IG_RegisterOnloadHandler(init); </script> <div id="two_id" style="display:none">Content for tab Two.</div>
<div id="three_id" style="display:none">This is static content for tab Three.</div> ]]>
</Content> </Module>

동적 콘텐츠 생성

위의 예에서는 콜백 함수를 사용하여 정적 콘텐츠를 탭에 추가합니다. 하지만 콜백은 동적 콘텐츠를 제공하는 데 더 많이 사용됩니다.

예를 들어, 본 샘플 가젯에서 콜백 함수는 사용자가 다른 탭을 클릭할 때마다 새로운 콘텐츠를 제공합니다. 콜백에서는 현재 날짜 및 시간을 초 단위까지 표시합니다. 따라서 다른 탭을 선택할 때마다 값이 변경됩니다.

가젯에서는 addDynamicTab(tab_name, callback_function) 함수를 사용합니다. 해당 함수는 'tab_name이라는 탭을 생성하고 callback_function을 사용하여 탭과 연관된 <div>를 콘텐츠로 채우도록' 탭 라이브러리에 지시합니다.

실행 중인 가젯은 다음과 같이 표시됩니다.

가젯 사양은 다음과 같습니다.

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="Dynamic Tabs"> 
    <Require feature="tabs" /> 
  </ModulePrefs>
  <Content type="html">
  <![CDATA[ 
    
    <script type="text/javascript"> 
    function init() {
        // Initialize tabs.
        var tabs = new _IG_Tabs(__MODULE_ID__); 

        // Technique #4: When you use addDynamicTab, the tab's content 
        // is dynamically generated through the callback function.
        tabs.addDynamicTab("One", callback);
        tabs.addDynamicTab("Two", callback); 
        tabs.addDynamicTab("Three", callback);
    }
    // Callback that displays the current date-time whenever a
    // new tab is clicked.
    function callback(tabId) {
        var date = new Date(); 
        _gel(tabId).innerHTML = date.toLocaleString();
    }

    // Call init function to initialize and display tabs.
    _IG_RegisterOnloadHandler(init);
    </script>
  ]]>
</Content> </Module>

다음은 좀 더 복잡한 실전 예제입니다.

인덱스를 기준으로 탭 조작

탭 API에는 또한 인덱스를 기준으로 탭을 조작할 수 있도록 하는 함수가 포함되어 있습니다. 탭 0부터 n까지 인덱싱되며 첫 번째 탭은 0입니다. 예를 들어, 3개의 탭이 있는 경우 인덱스는 0, 1 및 2입니다. 인덱스를 사용하여 탭을 프로그래밍 방식으로 선택하고 2개의 탭 위치를 전환할 수 있습니다.

탭 ID는 일정 상태로 유지되지만 인덱스는 그렇지 않습니다. 예를 들어, 세 번째 탭을 첫 번째 위치로 이동하면 인덱스는 2에서 0으로 변경됩니다.

다음은 탭을 프로그래밍 방식으로 선택하는 예입니다. 본 스니펫에서는 링크를 생성합니다. 사용자가 링크를 클릭하면 탭 자체를 클릭한 것처럼 두 번째 탭이 선택됩니다.

<script>
...
function selectTab() {
tabs.setSelectedTab(1);
}
</script> <a href="javascript:void(0)" onclick="selectTab()">Select Second Tab</a>

다음은 탭을 프로그래밍 방식으로 이동하는 예입니다. 본 스니펫에서는 링크를 생성합니다. 사용자가 링크를 클릭하면 가젯에서 첫 번째 탭과 두 번째 탭의 위치가 전환됩니다.

<script>
...
function switchTabs() {
tabs.moveTab(0, 1);
} </script> <a href="javascript:void(0)" onclick="switchTabs()">Switch Tabs</a>

맞춤형 탭 표시

탭 스타일시트는 http://www.google.com/ig/tablib.css로, 탭을 정의하는 HTML 요소에 적용되는 클래스를 정의합니다.

다음 CSS 클래스를 사용하여 기본 설정을 재정의하고 탭의 모양과 느낌을 수정할 수 있습니다.

CSS 클래스 설명
.tablib_table__MODULE_ID__ 셀이 들어 있는 HTML 테이블에 적용됩니다.
.tablib_selected__MODULE_ID__ 선택한 탭에 적용됩니다.
.tablib_unselected__MODULE_ID__ 선택한 모든 탭에 적용됩니다.
.tablib_spacerTab__MODULE_ID__ 각 탭 간의 공백 요소에 적용됩니다.
.tablib_emptyTab__MODULE_ID__ 탭 주위의 시작 공백과 끝 공백을 제어합니다.

참고사항: 특정 클래스를 재정의하는 경우 __MODULE_ID__를 포함해야 합니다. 이를 포함하지 않으면 코어 규칙을 재정의하는 경우 인라인 가젯의 탭이 손상됩니다.

다음은 가젯에서 CSS 설정을 재정의할 수 있는 방법에 대한 예입니다. 재정의할 수 있는 클래스 및 설정 목록을 보려면 http://www.google.com/ig/tablib.css를 참조하시기 바랍니다.

<![CDATA[ 
   <style type="text/css">     
     .tablib_selected__MODULE_ID__ { color: #FF0000; }
     .tablib_unselected__MODULE_ID__ { color: #660099; }
     .tablib_table__MODULE_ID__ { font-size:20px; }
     .tablib_emptyTab__MODULE_ID__ { padding:2px 5px; }
     .tablib_spacerTab__MODULE_ID__ { padding:0px 5px; }
   </style> 
<script...>

끌기

끌기 라이브러리를 사용하여 가젯에 끌기 기능을 추가할 수 있습니다. 끌기를 사용하려면 가젯 사양에 다음이 포함되어야 합니다.

끌기 라이브러리를 사용하여 사용자가 HTML 요소를 가젯 인터페이스로 끌어다 놓게 할 수 있습니다. 예를 들어, 여러 텍스트 요소를 샘플 가젯의 사진 위로 끌어다 놓습니다.

위 예는 끌기 라이브러리의 기본 개념에 대한 보기입니다.

마우스 버튼을 잡고 있는 동안 가젯에서는 사용자가 마우스를 이동하는 대상을 추적할 수 있습니다. 귀하는 사용자가 마우스 버튼을 놓는 시기를 파악할 수 있으며 필요에 따라 HTML을 변경하여 해당 이벤트에 응답할 수 있습니다.

끌기 라이브러리는 다음 표에 나와 있는 콜백 함수 위주로 작동합니다.

콜백 함수 설명
onDragStart = function(newSource) {} 끌기를 시작할 때 호출됩니다.
onDragTargetHit = function(newTarget, lastTarget) {} 끌기를 진행 중이고 대상에 도달한 경우에 호출됩니다.
onDragTargetLost = function(lastTarget) {} 끌기를 진행 중이고 사용자가 대상을 벗어난 경우에 호출됩니다.
onDragEnd = function(source, target) {} 끌기를 종료하여 사용자가 마우스 버튼에서 손가락을 뗀 경우에 호출됩니다.
onDragClick = function(source) {} 사용자가 마우스를 움직이지 않지만 마우스가 소스 위/아래로 이동하는 경우에 호출됩니다.

끌기 라이브러리의 함수 요약은 참조에서 확인하세요.

다음은 위의 예에 대한 가젯 사양입니다. 끌기 라이브러리를 사용하려면 <Require feature="drag"/> 태그가 <ModulePrefs> 섹션에 포함되어야 합니다. 각 HTML 요소에는 고유한 DOM ID가 지정됩니다. ID와 소스 및 대상을 추가하는 여러 가지 방법에 대한 자세한 내용은 소스 및 대상 추가 및 제거를 참조하시기 바랍니다.

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
<ModulePrefs title="Special Effects" scrolling="true" height="320">
<Require feature="drag" />
</ModulePrefs>
<Content type="html">
<![CDATA[
<table border=0>
<tr>
<td>
<p id="id1" style="font-weight:bold;">original</p>
<p id="id2" style="color:brown; font-weight:bold;">sepia</p>
<p id="id3" style="color:red; font-weight:bold;">red</p>
<p id="id4" style="color:green; font-weight:bold;">green</p>
</td>
<td id="id5" style="padding-left:60;">
<img src="http://doc.examples.googlepages.com/Rowan-small.gif" alt="Rowan"/>
</td>
</tr>
</table>
<script type="text/javascript">
// Preload the images
var images = new Object();
images["id1"] = new Image();
images["id1"].src = "http://doc.examples.googlepages.com/Rowan-small.gif";
images["id2"] = new Image();
images["id2"].src = "http://doc.examples.googlepages.com/Rowan-small-sepia.gif";
images["id3"] = new Image();
images["id3"].src = "http://doc.examples.googlepages.com/Rowan-small-red.gif";
images["id4"] = new Image();
images["id4"].src = "http://doc.examples.googlepages.com/Rowan-small-green.gif";
// drag constructor
var drag_obj = new _IG_Drag();
// Add sources and target. In this example, there is one target: the photo.
drag_obj.addSource("original", _gel("id1"), "<p style=color:orange;>Restore original...</p>");
drag_obj.addSource("sepia", _gel("id2"), "<p style=color:orange;>Change to sepia...</p>");
drag_obj.addSource("red", _gel("id3"), "<p style=color:orange;>Change to red...</p>");
drag_obj.addSource("green", _gel("id4"), "<p style=color:orange;>Change to green...</p>");
drag_obj.addTarget("image", _gel("id5"));
// When user drags source onto target and releases it,
// display appropriate photo.
drag_obj.onDragEnd = function(source, target) {
if (target == null) return;
target.innerHTML = "<img src='" + images[source.id].src + "'/>";
}
</script>
]]>
</Content>
</Module>

다음은 여러 HTML 요소의 위치를 바꿀 수 있는 좀 더 복잡한 예입니다.

다음은 위의 예에 대한 가젯 사양입니다. 모든 콜백 함수와, 끌기를 시작할 때 대리자가 있어야 하는 위치를 지정할 수 있는 _IG_Drag_surrogateOffset... 특성을 사용하는 방법에 대해 설명합니다. 다음 예에서는 여러 HTML 요소의 위치를 바꿀 수 있으므로 각 요소는 소스와 대상 모두가 됩니다.

<?xml version="1.0" encoding="UTF-8" ?> 
<Module>
  <ModulePrefs title="Drag Example" scrolling="true">
    <Require feature="drag" /> 
  </ModulePrefs>
  <Content type="html">
  <![CDATA[ 
    <table border=0><tr>
        <td id="demo1">
          Try dragging these 
        </td><td id="demo2">
          <img src="http://doc.examples.googlepages.com/different.gif" alt="different"/>
        </td>
     </tr><tr>
        <td id="demo3">
          <ul>
            <li>HTML
            <li>elements
            <li>around
          </ul>
        </td><td id="demo4">
          <table border=1><tr>
            <td>on</td>
            <td>this</td>
            <td>page.</td>
          </tr></table>
        </td>
    </tr></table>
 
    <script type="text/javascript">
    // drag constructor
    var demo = new _IG_Drag();

    // Add sources and targets, and assign them id's.
    demo.addSource("demo1");
    demo.addSource("demo2");
    demo.addSource("demo3");
    demo.addSource("demo4");
    demo.addTarget("demo1");
    demo.addTarget("demo2");
    demo.addTarget("demo3");
    demo.addTarget("demo4");

    // Set location of where each surrogate is at the start of a drag.
    _gel("demo1")._IG_Drag_surrogateOffsetY = 20;
    _gel("demo2")._IG_Drag_surrogateOffsetY = 0;
    _gel("demo3")._IG_Drag_surrogateOffsetY = -10;
    _gel("demo4")._IG_Drag_surrogateOffsetY = 20;

    // Render initial display of HTML elements
    var data = new Array();
    data[0] = "<B>(swap with this)</B>"
    data[1] = _gel("demo1").innerHTML;
    data[2] = _gel("demo2").innerHTML;
    data[3] = _gel("demo3").innerHTML;
    data[4] = _gel("demo4").innerHTML;
    var currentSource = null;

    // When drag starts, selected source HTML element is passed in callback;
    // here is is assigned as value to currentSource.
    demo.onDragStart = function (object) {
        currentSource = object;
    }

    // When user drags source object onto a target object, display text 
    // "swap with this"
    demo.onDragTargetHit = function (object, old_object) {
        demo.onDragTargetLost(old_object);
        if (object != currentSource)
          object.innerHTML = data[0];
    }

    // Called when drag is underway and user isn't on a target
    demo.onDragTargetLost = function (object) {
        if (object == null) return;
        if (object.id == "demo1") object.innerHTML = data[1];
        if (object.id == "demo2") object.innerHTML = data[2];
        if (object.id == "demo3") object.innerHTML = data[3];
        if (object.id == "demo4") object.innerHTML = data[4];
    }

    // When user drags source onto target and releases it, swap objects.
    // Update surrogate positions.
    demo.onDragEnd = function(source, target) {
        if (target == null) return;
        var src; var trg;
        for (var i=1; i!=5; ++i) {
          if (source.id == "demo" + i) src = i; 
          if (target.id == "demo" + i) trg = i; 
        }
        var temp = data[src];
        data[src] = data[trg];
        data[trg] = temp;
        _gel("demo" + src).innerHTML = data[src];
        _gel("demo" + trg).innerHTML = data[trg];
        temp = _gel("demo" + src)._IG_Drag_surrogateOffsetY;
        _gel("demo" + src)._IG_Drag_surrogateOffsetY = _gel("demo" + trg)._IG_Drag_surrogateOffsetY;
        _gel("demo" + trg)._IG_Drag_surrogateOffsetY = temp;
    }
    </script>
  ]]> 
  </Content>
</Module> 

소스 및 대상 추가 및 제거

위의 예에 나와 있듯이 _IG_Drag() 생성자를 사용하여 끌기 개체를 생성합니다.

var drag_obj = new _IG_Drag(); 

해당 예에서 여러 가지 방법으로 소스 및 대상을 생성할 수 있다는 것을 확인할 수 있습니다. 소스 및 대상은 끌기 ID(끌기 API에서 참조할 때 사용하는 ID)와 DOM ID(JavaScript에서 참조할 때 사용하는 ID)를 갖는 HTML 요소입니다. 소스 또는 대상을 추가할 때 끌기 ID를 지정하지 않으면 DOM ID가 끌기 ID로 사용됩니다. 예를 들어, <h2> 요소에 JavaScript ID "js-id1"가 지정되면 HTML 요소 선언을 살펴보세요.

<h2 id="dom-id1">My First Element</h2>

다음과 같은 방법으로 해당 HTML 요소를 소스로 추가할 수 있습니다.

// DOM ID becomes the drag ID 
drag_obj.addSource("dom_id1");
// Here the element is given a drag ID "first" which is different from the DOM ID.
drag_obj.addSource("first", _gel("dom_id1")); // A custom surrogate is included drag_obj.addSource("first", _gel("dom_id1"), "<b>This is my surrogate</b>");

소스 및 대상을 추가하고 제거하는 데 사용되는 함수 목록은 참조에서 확인하세요.

MiniMessage

MiniMessage는 가젯에서 사용자에게 표시되는 임시 메시지입니다. MiniMessage는 프로그래밍 방식으로 또는 사용자에 의해 취소되도록 만들어졌습니다. MiniMessage의 기본 유형은 다음과 같습니다.

MiniMessage를 사용하려면 가젯 사양에 다음이 포함되어야 합니다.

MiniMessage는 다음과 같이 사용할 수 있습니다.

다음은 본 섹션에서 설명한 여러 가지 방법을 보여 주는 MiniMessage 가젯의 입니다.

MiniMessage 라이브러리를 사용하는 실제 가젯에 대한 예를 보려면 동영상개발자 가젯을 참조하시기 바랍니다.

작동방식

가젯에 MiniMessage를 추가하려면 다음 단계를 따르세요.

1. MiniMessage 라이브러리를 가져옵니다.

<Require feature="minimessage"/>

2. _IG_MiniMessage() 생성자를 사용하여 새로운 MiniMessage 개체를 인스턴스화합니다.

var msg = new _IG_MiniMessage(__MODULE_ID__);

대부분의 경우 해당 개체를 모든 범위에서 액세스할 수 있는 하나의 글로벌 개체로 만드는 것이 좋습니다.

3. 일부 텍스트를 사용하여 새로운 MiniMessage를 생성합니다.

msg.createDismissibleMessage("Please close me when you're done reading me.");

위와 같이 하면 [x]가 연결된 상태의 취소 가능하고 서식이 설정된 메시지가 가젯의 맨 위에 추가됩니다. 사용자가 [x]를 클릭하면 메시지가 닫힙니다.

작업이 모두 끝났습니다! 여러 유형의 취소 가능한 메시지 중 하나를 작성했습니다.

서로 다른 위치에서 메시지 작성

기본적으로 메시지는 가젯 맨 위에 있는 컨테이너 HTML 요소 안에 위치합니다. 각각의 연속 메시지는 하위 요소로 위에서 아래로 컨테이너에 추가됩니다. 하지만 모든 메시지 또는 하나의 메시지에 대해 해당 동작을 수정할 수 있습니다.

모든 메시지의 위치 설정

HTML 요소(<div> 선호)를 생성자에 전달하여 메시지 컨테이너 요소의 기본 위치를 재정의할 수 있습니다. 해당 요소는 메시지가 삽입되고 표시되는 메시지 컨테이너가 됩니다.

예를 들어, 다음 스니펫에서 가젯 맨 위에 'I'm on top now!'라는 <h3> 메시지가 나타납니다. MiniMessage는 메시지가 추가된 순서대로 messageBox <div>에 표시됩니다.

<div>
<h3>I'm on top now!</h3>
</div>
<div id="messageBox"></div>
<script type="text/javascript"> // In the constructor, state that messages should be be displayed // in the messageBox <div> rather than at the top of the gadget. var msg = new _IG_MiniMessage(__MODULE_ID__, _gel("messageBox")); msg.createDismissibleMessage("I'm the first message."); msg.createDismissibleMessage("I'm the second message."); msg.createDismissibleMessage("I'm at the bottom."); </script>

단일 메시지의 위치 설정

메시지 컨테이너에 취소 가능한 메시지를 추가하지 않고 지정된 위치에서 해당 메시지를 작성할 수 있습니다. 이를 위해서는 가젯의 HTML 부분 안에 메시지를 표시한 다음 HTML 요소(<div> 선호)를 첫 번째 매개변수로 createDismissibleMessage()에 전달합니다.

예를 들어, 다음 스니펫에서는 status <div> 안에 메시지가 표시됩니다.

<div id="status" style="color:#B30000;">
<b>Check out our new API documentation!</b> -- <a href="http://www.google.com/apis/gadgets" target="_blank">Read</a>
</div>
<script type="text/javascript"> var msg = new _IG_MiniMessage(__MODULE_ID__); // Pass the HTML element to createDismissableMessage() to indicate // where the message should be displayed. msg.createDismissibleMessage(_gel("status")); </script>

DOM 방식을 사용하여 메시지 작성

HTML DOM 방식을 사용하여 취소 가능한 메시지를 생성해야 하는 경우가 있습니다. DOM에 해당 메시지가 없기 때문에 기본적으로 메시지 컨테이너에 추가됩니다.

예:

<script type="text/javascript"> 
  var msg = new _IG_MiniMessage(__MODULE_ID__);
  // Generate the message using DOM methods
  var div = document.createElement("div");
  div.innerHTML = "New message created by W3C DOM methods.";
  // Set some DOM properties
  div.onmouseover = function() {
    div.style.backgroundColor = "green";
  };
  div.onmouseout = function() {
    div.style.backgroundColor = "";
  };
  msg.createDismissibleMessage(div);
</script>

타이머 메시지 작성

타이머 메시지는 일정 시간(초)이 지난 후 사라지는 서식이 설정된 메시지입니다. createTimerMessage() 함수는 2개의 매개변수, 즉 메시지 문자열과 메시지를 표시해야 하는 시간(초)을 표시하는 숫자를 사용합니다. 다음은 해당 예입니다.

var msg = new _IG_MiniMessage(__MODULE_ID__);
msg.createTimerMessage("I'm going to disappear in 5 seconds.", 5);

정적 메시지 작성

정적 메시지는 메시지가 프로그래밍 방식으로 dismissMessage() 함수에 의해 취소될 때까지 표시되는 서식의 메시지입니다. 해당 메시지는 가젯에서 콘텐츠 가져오기와 같은 백그라운드 작업을 수행할 때 사용자에게 알려주는 알림 메시지를 표시할 때 유용합니다.

다음 예에서 정적 메시지는 사용자에게 가져오기가 진행 중임을 알려주기 위해 표시됩니다. 가져오기가 완료되면 메시지는 사라집니다.

<div id="loading">Fetching content...</div>

<script type="text/javascript">
  var msg = new _IG_MiniMessage(__MODULE_ID__);
  var loadMessage = msg.createStaticMessage(_gel("loading"));

  _IG_FetchXmlContent('http://www.google.com/', function(responseText)
  {
    alert(responseText.substr(0,400));
    msg.dismissMessage(loadMessage);
  });
</script>

맞춤형 MiniMessage 표시

다음 2가지 방법으로 MiniMessage의 기본 모양을 변경할 수 있습니다.

개별 메시지의 스타일 변경

DOM 함수를 사용하여 메시지의 스타일을 변경할 수 있습니다. 취소 가능한 새 메시지를 작성하는 경우 HTML 요소가 반환됩니다. 반환된 HTML 요소의 스타일 특성을 설정하여 메시지의 모양을 수정할 수 있습니다. 다음은 해당 예입니다.

<script>
  var msg = _IG_MiniMessage(__MODULE_ID__);
  var statusMsg = msg.createDismissibleMessage("This is a critical error!");
  // Change the message's background color to red
  statusMsg.style.backgroundColor = "red";
  statusMsg.style.color = "white";
</script>

참고: 이 예에서는 메시지의 전체 배경색을 변경하는 올바른 방법을 보여 줍니다. 메시지가 포함된 <div>의 배경색을 설정해도 전체 배경색이 변경되지는 않습니다.

모든 메시지의 스타일 변경

CSS를 사용하여 모든 메시지의 스타일을 전체적으로 변경할 수 있습니다. MiniMessage 스타일시트는 http://www.google.com/ig/minimessagelib.css로, MiniMessage를 정의하는 HTML 요소에 적용되는 클래스를 정의합니다.

다음 CSS 클래스를 사용하여 기본 설정을 재정의하고 메시지의 모양과 느낌을 수정할 수 있습니다.

CSS 클래스 설명
.mmlib_table__MODULE_ID__ 메시지가 포함된 HTML 테이블에 적용됩니다.
.mmlib_xlink__MODULE_ID__ 메시지를 취소하는 데 사용되는 [x] 링크에 적용됩니다. 해당 설정은 메시지를 취소할 때만 적용됩니다.

예를 들어, 다음은 배경색을 군청으로, 전경색을 흰색으로 변경합니다.

<![CDATA[
   <style>
     .mmlib_table__MODULE_ID__ {
       background-color: #000066;
       color: #ffffff;
     }
   </style>
<script...>

그리드

그리드 라이브러리를 사용하여 가젯에 그리드 기능을 추가할 수 있습니다. 그리드 라이브러리를 사용하려면 가젯 사양에 다음이 포함되어야 합니다.

그리드 라이브러리는 끌기 라이브러리와 함께 작동하여 그리드 기반 사용자 인터페이스를 제공합니다. 다음 예에서는 그리드 라이브러리의 기본 개념에 대해 설명합니다. 오른쪽의 X와 O를 그리드의 원하는 위치로 끌면서 Tic Tac Toe(멀티플레이어)를 재생할 수 있습니다.

작동방식

그리드는 일반적으로 다음과 같은 요소로 구성됩니다.

그리드 라이브러리를 사용하려면 다음 단계를 따르세요.

1. 그리드 라이브러리를 가져옵니다.

<Require feature="grid"/>

2. 백엔드 개체를 작성하고 선택적으로 일부 데이터로 해당 개체를 초기화합니다.

var ttt_backend = new Object();
    ttt_backend.data = new Array(".",".","."," ","X",
".",".","."," ","O",
".",".","."," "," ");

백엔드 개체는 그리드에 표시되는 콘텐츠를 관리합니다. 백엔드 개체는 최소한 그리드의 항목이 소스와 대상인 경우와 모양을 알아야 합니다. 일반적으로 그리드에는 데이터가 표시되고 해당 데이터는 대개 백엔드 개체에 저장됩니다.

3. 새로운 _IG_Grid object:를 작성합니다.

var ttt_grid = new _IG_Grid(ttt_backend, "tictactoegrid", 3, 5);

_IG_Grid 생성자는 첫 번째 매개변수로 백엔드 개체를 사용합니다. 두 번째 매개변수는 그리드에 사용되는 모든 DOM 개체의 ID 필드에 접두사가 추가되는 그리드의 고유한 ID입니다. 해당 문자열을 접두사로 사용하여 이름을 지정하지 않아야 합니다. 세 번째 및 네 번째 매개변수는 각각 그리드의 높이와 너비입니다.

4. 그리드의 콘텐츠를 표시합니다.

grid.getTable().border = 2; 
grid.getTable().cellPadding = 5;
_gel("grid_table").appendChild(grid.getTable());

grid.getTable()은 그리드의 HTML 테이블에 포함된 DOM 개체를 반환합니다. 다른 DOM HTML 테이블과 마찬가지로 해당 설정을 변경할 수 있습니다. 가젯에 표시하려면 appendChild() 함수를 사용하세요.

5. 그리드에서 끌기를 감지할 수 있도록 만듭니다.

grid.initDragging(); 

6. 필수 백엔드 함수를 구현합니다.

그리드 라이브러리를 사용하려면 다음 백엔드 함수를 구현해야 합니다. 구현 샘플을 보려면 를 참조하시기 바랍니다.

함수 설명
_IGG_getNormalView(index) 사용자가 끌기 작업을 하지 않을 때 표시되도록 index의 셀에 있는 기본 HTML 콘텐츠를 반환합니다.
_IGG_isDragSource(index) index의 요소가 끌기 소스인지 여부를 나타내기 위한 부울 값을 반환합니다.
_IGG_isDragTarget(index, sourceIndex) sourceIndex가 끌기 소스인 경우 index의 요소가 끌기 대상인지 여부를 나타내기 위한 부울 값을 반환합니다.

그리드 라이브러리의 전체 함수 목록은 참조에서 확인하세요.

간단한 그리드 예

다음은 위에 표시된 Tic Tac Toe(멀티플레이어) 예에 대한 가젯 사양입니다.

<?xml version="1.0" encoding="UTF-8" ?>
<Module> <ModulePrefs title="Grid Test" > <Require feature="grid"/> </ModulePrefs> <Content type="html"> <![CDATA[ <span id="ttt_table"></span> <script type="text/javascript"> var ttt_backend = new Object(); ttt_backend.data = new Array(".",".","."," ","X",
".",".","."," ","O",
".",".","."," "," "); // Required backend function. Returns the default HTML content of the cell at index // to be displayed when the user is not dragging. ttt_backend._IGG_getNormalView = function(index) { return this.data[index]; } // Required backend function. Returns a boolean value to indicate whether the element // at index is a drag source. ttt_backend._IGG_isDragSource = function(index) { return (index == 4 /* X */ || index == 9 /* O */); } // Required backend function. Returns a boolean value to indicate whether the element // at index is a drag target when sourceIndex is a drag source. ttt_backend._IGG_isDragTarget = function(index, sourceIndex) { return (index % 5 == 0 || index % 5 == 1 || index % 5 == 2); } ttt_backend._IGG_handleDrag = function(source, target) { this.data[target] = this.data[source]; this._IGG_refreshCell(source); this._IGG_refreshCell(target); this.checkWin(); } ttt_backend.check_three_in_a_row = function(p1, p2, p3) { /* if p1 p2 p3 are all the same and not empty, change the win display. */ if (this.data[p1] == ".") return; if (this.data[p1] != this.data[p2]) return; if (this.data[p1] != this.data[p3]) return; this.data[14] = this.data[p1] + " wins!"; this._IGG_refreshCell(14); } ttt_backend.checkWin = function() { this.check_three_in_a_row(0,1,2); this.check_three_in_a_row(0,5,10); this.check_three_in_a_row(0,6,12); this.check_three_in_a_row(1,6,11); this.check_three_in_a_row(2,6,10); this.check_three_in_a_row(2,7,12); this.check_three_in_a_row(5,6,7); this.check_three_in_a_row(10,11,12); } // Create a new grid object var ttt_grid = new _IG_Grid(ttt_backend, "tictactoegrid", 3, 5); // The function grid.getTable() returns the DOM object that contains the // HTML table for the grid. You can change its settings just like any other // DOM HTML table. ttt_grid.getTable().border = 2; ttt_grid.getTable().cellPadding = 5; // Displays the table in your gadget. _gel("ttt_table").appendChild(ttt_grid.getTable()); // Makes the grid sensitive to dragging. ttt_grid.initDragging(); </script> <div id="content_div"></div> ]]> </Content>
</Module>

추가 정보

위의 예는 동적 콘텐츠를 표시하고 끌기 동작에 반응하는 기본 그리드를 생성하는 방법을 보여 줍니다. 본 섹션에서는 그리드에 좀 더 복잡한 동작을 추가하는 데 사용할 수 있는 그리드 라이브러리 함수에 대해 설명합니다.

그리드 백엔드 표시 함수

기본적으로 그리드 라이브러리는 셀 콘텐츠를 표시하려고 할 때마다 getNormalView()를 호출합니다. 하지만 사용자의 끌기 방식에 따라 셀 콘텐츠가 다르게 반응하여 표시되게 할 수 있습니다. 이런 경우 백엔드 개체에 대해 다음 옵션 함수를 구현할 수 있습니다. 이러한 함수의 사용 방법은 고급 그리드 예를 참조하세요.

함수 설명
_IGG_getSurrogateView(index) index의 콘텐츠를 끌 때 대리자 보기(마우스 커서 아래에 표시)의 HTML 콘텐츠를 반환합니다.
_IGG_getSourceView(source, target) 사용자가 끌 때 source가 되는 셀의 HTML 콘텐츠를 반환합니다. 마우스 커서가 대상 위에 있는 경우 target은 대상의 인덱스를 포함합니다. 그렇지 않으면 -1을 포함합니다.
_IGG_getTargetView(target, source) target인 경우 사용자가 끌 때 셀의 HTML 콘텐츠를 반환합니다. source는 소스의 인덱스입니다.
_IGG_getPossibleTargetView(potential_target, source) potential_target인 경우(대상이 아님) 사용자가 끌 때 셀의 HTML 콘텐츠를 반환합니다. source는 소스의 인덱스입니다.
_IGG_getDragView(index, source) 잠재적인 대상이 아니고 소스도 아닌 경우 사용자가 끌 때 index의 셀 HTML 콘텐츠를 반환합니다. source는 소스의 인덱스입니다.

그리드 백엔드 반응 함수

그리드 라이브러리는 가젯이 마우스 클릭 및 끌기에 응답할 수 있도록 다음과 같은 함수를 제공합니다. 이러한 함수의 사용 방법은 고급 그리드 예를 참조하세요.

함수 설명
_IGG_handleClick(source) 사용자가 source를 클릭하면(즉, 마우스를 끌지 않고 mouseDown 및 mouseUp을 수행하는 경우) 호출됩니다.
_IGG_handleDragStart(source) 사용자가 source에 대해 mouseDown을 수행한 다음 끌기 과정을 시작한 경우에 호출됩니다.
_IGG_handleDrag(source, target) 끌기를 종료한 경우에 호출됩니다. 사용자가 유효한 대상에서 종료한 경우 target은 대상 인덱스를 포함합니다. 그렇지 않으면 -1 값을 갖습니다.
_IGG_handleClick()을 호출하면 _IGG_handleDrag()도 호출됩니다. 따라서 응용 프로그램에 따라 _IGG_handleDrag()만 사용하는 것이 좋습니다.

그리드 백엔드 콜백

백엔드 콜백 함수는 백엔드 개체에서 자동으로 생성됩니다. 그리드 라이브러리에서는 필요에 따라 콜백 함수를 호출하지만 사용자 끌기 이외의 프로세스를 통해 데이터를 변경하는 경우와 같이 사용자가 직접 해당 함수를 호출할 수도 있습니다. 그리드 라이브러리에는 다음과 같은 백엔드 콜백이 포함되어 있습니다.

함수 설명
_IGG_refreshCell(index) index의 셀 표시를 새로 고칩니다.
_IGG_refreshAll() 모든 셀의 표시를 새로 고칩니다. 해당 작업은 특히 그리드가 복잡하고 용량이 큰 경우 시간이 오래 걸릴 수 있습니다.

셀을 새로 고치는 경우

사용자의 끌기가 종료되면 셀이 다음과 같이 새로 고쳐집니다.

따라서 고급 보기는 정의하지 않았지만 _IGG_handleDrag()를 정의했거나 정의하려는 경우 끌기의 효과를 사용자에게 표시하려면 _IGG_refreshCell() 콜백을 호출해야 합니다.

고급 그리드 예

다음은 위의 추가 정보 섹션에서 설명한 함수 사용 방법에 대한 예입니다.

그리드의 동작은 다음과 같습니다.

샘플 가젯 사양은 다음과 같습니다.

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
<ModulePrefs title="Advanced Grid Demo"
height="250" > <Require feature="grid"/> </ModulePrefs> <Content type="html"> <![CDATA[ <span id="grid_table"></span> Dragging: <span id="sdat">??</span> <script language="JavaScript"> // Create backend object, initialize with data var backend = new Object(); backend.data = new Array(1,2,3,4,5,6,7,2,1,7,4,5,6,3,5,7,3,6,4,1,2,7,6,5,4,3,2,1); // Default for cell content display backend._IGG_getNormalView = function(index) { var value = this.data[index]; return '<span style="font-size:24pt">' + value + '</span>'; } backend._IGG_isDragSource = function(index) { return true; } backend._IGG_isDragTarget = function(index, sourceIndex) { return this.data[index] != this.data[sourceIndex]; } // Returns the HTML content to be displayed under the cursor during a drag.
// In this example the surrogate view is the source value, bolded. backend._IGG_getSurrogateView = function(index) { var value = this.data[index]; return '<span style="font-size:24pt"><b>' + value + '</b></span>'; } // If the cursor is over a target, returns "source-value → target-value"
// in gray font for display in the source cell. Otherwise, returns source value. backend._IGG_getSourceView = function(source, target) { var s_value = this.data[source]; if (target == -1) { return '<span style="font-size:24pt;color:#888888">' + s_value + '</b></span>'; } else { var t_value = this.data[target]; return '<span style="font-size:10pt;color:#888888">' + s_value + '→' + t_value + '</b></span>'; } } // Returns the HTML content of cells that are legitimate targets for a drag operation. // In this example, a cell is a legitimate target if its value doesn't match the source value. // Cells that are legitimate targets display text in green. Cells that are not legitimate targets // display text in red, via the _IGG_getDragView() function below. backend._IGG_getPossibleTargetView = function(target, source) { var t_value = this.data[target]; // If a cell is a legal target, display its contents in a green font. return '<span style="font-size:24pt;color:#00A000">' + t_value + '</b></span>'; } // Returns the HTML content of cells that are NOT legitimate targets for a drag operation. // Cells that are not legitimate targets display text in red. // Cells that are legitimate targets display text in green via the _IGG_getPossibleTargetView() // function, above. backend._IGG_getDragView = function(target, source) { var t_value = this.data[target]; // If a cell is NOT a legal target, display its contents in a red font. return '<span style="font-size:24pt;color:#FF0000">' + t_value + '</b></span>'; } // If the cursor is over a target, returns "source-value + target-value"
// in green font for display in the target cell. backend._IGG_getTargetView = function(target, source) { var t_value = this.data[target]; var s_value = this.data[source]; return '<span style="font-size:12pt;color:#00A000">' + t_value + '+' + s_value + '</b></span>'; } // Clicking on a cell without dragging increments the value of the // cell's contents by 1. backend._IGG_handleClick = function(source) { this.data[source]++; // Callback on the backend object to force refresh this._IGG_refreshCell(source); } // When the user starts dragging, changes the message underneath the grid to show // the number that is being dragged. backend._IGG_handleDragStart = function(source) { document.getElementById("sdat").innerHTML = this.data[source]; } // If the user didn't drag to a legal target, don't change the data, but refresh the source // cell. Otherwise, adjust the numbers, and refresh the changed cells.
backend._IGG_handleDrag = function(source, target) { if (target == -1) { this._IGG_refreshCell(source); } else { this.data[target] += this.data[source]; this.data[source] = 0; // Callback on the backend object to force refresh this._IGG_refreshCell(source); this._IGG_refreshCell(target); } document.getElementById("sdat").innerHTML = '??'; } var grid = new _IG_Grid(backend, "mygrid", 4, 7); grid.getTable().border = 2; grid.getTable().cellPadding = 5; _gel("grid_table").appendChild(grid.getTable()); grid.initDragging(); </script> ]]>
</Content>
</Module>

그리드 라이브러리의 전체 함수 목록은 참조에서 확인하세요.

Back to top

업데이트 날짜: