'3. Implementation/VB / Java Script'에 해당되는 글 34건
- 2009.09.13 키 입력시 지정된 키 이벤트 처리를 무시하기
- 2009.09.13 TextArea 자동 크기 맞춤 & 이미지 사이즈 맞추기와 클릭시 원본 사이즈 보여주기
- 2009.07.21 Drag & Drop 예
- 2009.07.21 테이블을 보였다가 숨기는 Jscript
- 2009.07.08 동적으로 생성한 엘리먼트에 이벤트 추가하기
- 2009.07.08 TextArea 크기 자동 맞추기
- 2009.07.07 [펌] 동적으로 생성한 radio, checkbox 가 클릭되지 않을 때
- 2009.07.04 innerHTML, innerText, outerHTML, outerText 사용하기
- 2009.07.04 [Javascript] 이미지 preloading 이용하기
- 2009.07.04 [JavaScript] Custom Window 띄우기
- 2009.07.03 동적으로 테이블 행 추가/삭제 하기
- 2009.06.16 비활성(disable)하지 않고 읽기 전용(Readonly) 텍스트 상자 만들기
- 2009.05.25 Resizing an iframe according to its contents
- 2009.05.20 How to include a file from within a VBScript script
키 입력시 지정된 키 이벤트 처리를 무시하기
이걸 몰라서 text 값에서 비교해 가면서 삭제했던 기억이.... ^^; 아는게 힘이다!
<html> <head> <script type="text/javascript" language="javascript"> //<!-- function noctrlalt(){ if(event.ctrlKey || event.altKey ) { event.returnValue=false; } }//Ctrl키 와 Alt키가 안먹히게 처리함. var KEYCODE_A = 65; function noa() { if(event.keyCode == KEYCODE_A) { event.returnValue=false; } // alert(event.keyCode); } //--> </script> </head> <body> <!-- Ctrl 과 alt 키가 눌러져 있으면 모든 키 이벤트를 무시한다. --> <input type="text" onkeydown="noctrlalt();" size="10" /> <!-- 아래는 a키를 무시한다. --> <input type="text" onkeydown="noa();" size="10" /> </body> </html> |
참고 : http://heavening.tistory.com/16
TextArea 자동 크기 맞춤 & 이미지 사이즈 맞추기와 클릭시 원본 사이즈 보여주기
<html> function resize_popup() |
이미지 관련은
아래 글 참고
Drag & Drop 예
<html> <head> <script type="text/javascript"> var isDown=true; var x=0 , y=0 ; function start(){ if (event.srcElement.id=="myImg"){ isDown=true ; x = event.clientX - document.all.myImg.style.pixelLeft; y = event.clientY - document.all.myImg.style.pixelTop; document.onmousemove
= move; } } function move(){ if (isDown&&event.button==1) { document.all.myImg.style.pixelLeft = event.clientX - x; document.all.myImg.style.pixelTop = event.clientY - y; return false } } function stop(){ isDown=false; } document.onmousedown
= start; document.onmouseup
= stop; </script> </head> <body> <img id="myImg" src="person1.gif"
style="position:relative"> <h2>Drag & Drop 하세요</h2> </body> </html> |
출처 : 삼성 SDS e-Campus 의 "JavaScript 쉽고 빠르게" 과정 중에서
테이블을 보였다가 숨기는 Jscript
<html> <script type="text/javascript"> function toggleTable()
{ toggleObj(target); } function toggleDiv() { toggleObj(test); } function toggleObj(obj) { if ( obj.style.visibility
== "visible" ) { obj.style.visibility = "hidden"; } else { obj.style.visibility = "visible"; } } </script> <body> <input type="button" onclick="toggleDiv();" value="전체토글" /> <input type="button" onclick="toggleTable();" value="테이블만토글" /><p></p> <div id="test" >보일까말까? <table border="1"><tr><td>Div 에묶여있는테이블</td></tr></table> </div> <p></p> <table id="target" border="1"><tr><td>토글될테이블</td></tr></table> </body> </html> |
아래는 실행 화면.
동적으로 생성한 엘리먼트에 이벤트 추가하기
1. attachEvent 메소드를 이용,
2. 동적으로 function 객체를 생성하여 할당
등이 있다. 첫번째 방법은 파라미터를 전달할 수 없으나, 두번째 방법은 파라미터를 마음대로 전달할 수 있다.
사용예는 아래를 참고바람.
<html> <head> <title></title> </head> <script type="text/javascript"> function OnClick1()
{ alert(event.srcElement.name); } function MyAlert(id, msg) { alert(id + " : " + msg); } function createButton() { var newRow = target.insertRow(); var newTd = newRow.insertCell(); var newInput = document.createElement("input"); newInput.setAttribute("type", "button"); newInput.setAttribute("value", "AttachEvent
Test"); newInput.attachEvent("onclick", OnClick1); newInput.name =
"First Input"; newTd.appendChild(newInput); newInput = document.createElement("input"); newInput.setAttribute("type", "button"); newInput.setAttribute("value", "Dynamic
Event Test"); newInput.name =
"Second Input"; newInput.onclick
= function() { MyAlert(newInput.name, "Possible
to pass many parameters dynamically!!"); } newTd.appendChild(newInput); } </script> <body> <input type="button"
value="New
Buttons" onclick="createButton()" /><p></p> <table id="target"> </table> </body> </html> |
TextArea 크기 자동 맞추기
업데이트 : 2009-07-08
스크롤바 크기를 비교하여 복잡하게 하는 것보다, 그냥 스타일 쉬트에 다음을 적용하는게 훨씬 쉽다.
overflow:visible; |
아래는 프로그래밍적으로 해결.
<style type="text/css"> .NoScroll { overflow:hidden; } </style> <script type="text/javascript" language="javascript"> function onFitSizeOfTextArea() { var textArea = event.srcElement; while( textArea.clientHeight < textArea.scrollHeight ) { textArea.rows =
textArea.rows
+ 1; } textArea.className
= "NoScroll"; } </script> <textarea cols="50" rows="3" onclick="onLoadTextArea();" >Some long text…</textarea> |
컨셉은 굉장히 단순하다. Textarea 의 스크롤 높이가 Textarea 의 클라이언트 높이보다 작거나 같을때까지 row를 하나씩 증가시키는 것이다. onload 라는 이벤트 핸들러가 없어서 테스트는 onClick 이벤트에다가 핸들러를 추가했는데 이걸 응용하여 어떻게든 적용할 수 있을 것이다.
또한, NoScroll 스타일을 적용하여 스크롤을 없앴다.
CSS 와 프로그래밍에는 각기 장점이 있으므로 경우에 따른 방법을 사용하자.
[펌] 동적으로 생성한 radio, checkbox 가 클릭되지 않을 때
function createRadio(name, value) { var obj; try { obj = document.createElement("<input type='radio' name='"+name+"' />"); } catch(e) { obj = document.createElement("input"); obj.type = "radio"; obj.name = name; } obj.value = value; document.forms[0].appendChild(obj); } |
위 소는 IE와 IE가 아닌 브라우저에서 동작하도록 예외를 이용하였다.
업데이트 : 2009-07-09
동적으로 생성한 radio 버튼은 checked 속성으로 선택이 되지 않는 문제가 발생하였다. 이 역시 생성 시에 "CHECKED" 를 넣어주면 된다.
obj = document.createElement("<input type='radio' name='"+name+"' CHECKED />"); |
원본 : http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=43884
innerHTML, innerText, outerHTML, outerText 사용하기
innerText 는 단순히 텍스트만 넣을 수 있다.
outerHTML 은 아예 태그까지 변경한다.
outerText 는 내용을 바꾸되 새로운 태그는 넣을 수 없고 다만 텍스트만 넣을 수 있다.
<html> <head> <style type=text/css> h2 {color:blue; text-align:center} </style> </head> <body> <h2 onClick="this.innerHTML= '<div>이문장이<i>innerHTML</i>입니다.</div>'"> 클릭하시면 내용을변경하실수있습니다. </h1> <h2 onClick="this.innerText= '<div>이문장이innerText입니다.</div>'"> 클릭하시면내용을변경하실수있습니다. </h2> <h2 onClick= "this.outerHTML='<div>이문장이<i>outerHTML</i>입니다.</div>'"> 클릭하시면내용을변경하실수있습니다. </h2> <h2 onClick= "this.outerText='<div>이문장이outerText 입니다.</div>'"> 클릭하시면내용을변경하실수있습니다. </h1> </body> </html> |
실행 결과 :
참고 : 삼성 SDS 멀티캠퍼스 : JavaScript 쉽고 빠르게 과정 중에서
[Javascript] 이미지 preloading 이용하기
<html> <head> <script type="text/javascript"> var i = 1; var imageArr = new Array(); function preload(){ for (i = 1; i <=
4; i++){ imageArr[i] = new Image(); imageArr[i].src = "preload"+i+".gif"; } } function changeImage(){ if (i > 4) i =
1; document.image1.src = imageArr[i].src; i
++; } </script> </head> <body onLoad="preload()"> <a href="#" onClick=changeImage()><img name=image1 src="preload4.gif"
border=0></a> </body> </html> |
참고 : 삼성 SDS 멀티캠퍼스 [Java Script 쉽고 빠르게] 참고
[JavaScript] Custom Window 띄우기
<html> <head> <script type=text/javascript> <!-- function openWin(){ win1
= window.open('','','width=100,height=100'); win1.document.open(); win1.document.write("<html><body>"); win1.document.write("HELLO~<br>"); win1.document.write("</body></html>"); win1.document.close(); } //--> </script> </head> <body> <form> <input type=button onClick="openWin();"
value="열기"> </form> </body> </html> |
document 내장 객체를 이용하여, open, write, close 순서로 한다.
동적으로 테이블 행 추가/삭제 하기
1. 동적으로 테이블에 행 추가하기
2. 동적으로 테이블에 행 삭제하기
3. 동적으로 엘리먼트에 이벤트 할당하기
4. 이벤트 핸들러에서 event.srcElement 를 통해서 원본 엘리먼트 가져오기등
* 업데이트 : 2009-07-08
TR 과 TD 추가시 TBODY 를 사용하지 말고 TABLE 의 메소드를 호출하여 구현하는 것이 더 좋다. 그렇게 하면, 코드도 깔끔해지면서 TBODY 를 사용하면서 나타나는 여러가지 문제를 사전에 예방할 수 있다.
아래 소스는 appendChild 를 따로 호출할 필요가 없다.
function AppendTrAndTd() { var newRow = tbl.insertRow(); var newTD = newRow.insertCell(); } |
아래 소스는 모두 insertRow 와 insertCell 로 변경해야 한다.
<!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> <title></title> </head> <script type="text/javascript" language="javascript"> function NewRow() { var tBody = tbl.getElementsByTagName("tbody")[0]; var row = MakeNewRow(); tBody.appendChild(row); } function InsertUpper() { InsertRow (event.srcElement, true); } function InsertLower() { InsertRow(event.srcElement, false); } function InsertRow(obj, ToUpper) { var TargetRow; TargetRow = obj.parentNode; while(TargetRow != null) { if( TargetRow.nodeName == "TR" ) { break; } TargetRow = TargetRow.parentNode; if(TargetRow == document) { TargetRow = null; break; } } if(TargetRow == null) return; var newRow = MakeNewRow(); var tBody = tbl.getElementsByTagName("tbody")[0]; if (ToUpper == true) { tBody.insertBefore(newRow, TargetRow); } else { TargetRow = TargetRow.nextSibling; if(TargetRow != null) { tBody.insertBefore(newRow, TargetRow); } else { tBody.appendChild(newRow); } } } function MakeNewRow() { // check box var newRow = document.createElement("tr"); var newTd = document.createElement("td"); var newInput = document.createElement("input"); newInput.setAttribute("type", "checkbox") newTd.appendChild(newInput); newRow.appendChild(newTd); // Description newTd = document.createElement("td"); var newTextArea = document.createElement("textarea"); newTextArea.setAttribute("cols", "50"); newTextArea.setAttribute("rows", "3"); newTd.appendChild(newTextArea); newRow.appendChild(newTd); // Expected Result newTd = document.createElement("td"); var newTextArea = document.createElement("textarea"); newTextArea.setAttribute("cols", "50"); newTextArea.setAttribute("rows", "3"); newTd.appendChild(newTextArea); newRow.appendChild(newTd); // buttons newTd = document.createElement("td"); newInput = document.createElement("input"); newInput.setAttribute("type", "button"); newInput.setAttribute("value", "△"); newInput.attachEvent("onclick", InsertUpper); newTd.appendChild(newInput); var newBr = document.createElement("br"); newTd.appendChild(newBr); newInput = document.createElement("input"); newInput.setAttribute("type", "button") newInput.setAttribute("value", "▽") newInput.attachEvent("onclick", InsertLower); newTd.appendChild(newInput); newRow.appendChild(newTd); return newRow; } function deleteCheckedRow() { var inputList = document.getElementsByTagName("input"); var tBody = tbl.getElementsByTagName("tbody")[0]; var checkItem; for(var i=inputList.length-1; i >= 0; i--) { checkItem = inputList.item(i); if( checkItem.checked == true) { var nodeParent = checkItem.parentNode.parentNode; if(nodeParent.nodeName == "TR") { tBody.removeChild(nodeParent); } } } } </script> <body> <!--<input type="button" value="Java : New Step" onclick="javascript:MakeNewRow()" /> <p></p> <input type="button" value="VBScript : New Step" onclick="vbscript:MakeNewRow()" /> <p></p>--> <input type="button" value="Delete checked items" onclick="javascript:deleteCheckedRow()" /> <input type="button" value="New Row" onclick="javascript:NewRow()" /> <p></p> <table id="tbl" border="1" > <tr> <th></th> <th>Description</th> <th>Expected Result</th> <th></th> </tr> <tr> <td><input type="checkbox" /></td> <td><textarea cols="50" rows="3"></textarea></td> <td><textarea cols="50" rows="3"></textarea></td> <td> <input type="button" value="△" onclick="javascript:InsertRow(this, true)" /><br /> <input type="button" value="▽" onclick="javascript:InsertRow(this, false)" /> </td> </tr> </table> </body> </html> |
비활성(disable)하지 않고 읽기 전용(Readonly) 텍스트 상자 만들기
<input onfocus="javascript:blur();" style="cursor: default;" type="text" name="inputname" value="inputvalue" size=20> |
style="cursor:default"
Resizing an iframe according to its contents
After we learned how to create an iframe with a height of 100%, I'll show you how to create an iframe that gets its height according to the contents of the page that is in it.
That way if you have a long page inside your iframe then your iframe will be tall enough so that you can scroll the external page without scrolling the iframe itself.
You may find this useful in certain cases but I recommend not using it unless you really need it (since you may miss the entire point of using an iframe in the first place).
The Code
In the head of your document enter the following JavaScript code:<script language="JavaScript">
<!--
function calcHeight()
{
//find the height of the internal page
var the_height=
document.getElementById('the_iframe').contentWindow.
document.body.scrollHeight;
//change the height of the iframe
document.getElementById('the_iframe').height=
the_height;
}
//-->
</script>
and in the body create the iframe tag:<iframe width="700" id="the_iframe"
onLoad="calcHeight();"
src="testing_page.shtml"
scrolling="NO"
frameborder="1"
height="1">
An iframe capable browser is
required to view this web site.
</iframe>
If you decide to use this code all I ask is that you let me know.
Thanks to all the people who sent me their comments on this code and helped me improve it :o)
이 코드 사용시 주의점 : 이 코드를 사용하게 되면 코드를 사용한다고 저자에게 알려주면 좋겠다 함.
출처 : http://guymal.com/mycode/iframe_size/
관련 한글 사이트 : http://www.webmini.net/19888
Update : 2009-06-23
위 코드로 제대로 동작하지 않을때가 있다. iframe src 가 동적으로 변경되는 경우. 이때는 다음과 같이 하여 해결하였다.
<script type="text/javascript" language="javascript" > <!-- function autoResize(obj) { param = "TimeFunc('"
+ obj.id
+ "')"; setTimeout(param,
10); } function TimeFunc(name) { obj = document.getElementById(name) cwindow = (obj).contentWindow; if (cwindow != null) { var iframeHeight= (obj).contentWindow.document.body.scrollHeight; (obj).height = iframeHeight; } } --> </script> <iframe id="test" src="" scrolling="auto" onload="javascript:autoResize(this)" width="100%" frameborder="0" height="0" ></iframe> |
How to include a file from within a VBScript script
아래는 VBScript 에서 다른 VBScript 파일을 포함하는 방법에 대해서 설명하였다.
VBScript 5.6 does not provide a statement to include files. But the ExecuteGlobal statement can be used to include program code from a file. The test program below shows how to do it.
Example of how to call the test program:
cscript TestIncludeFile.vbs
TestIncludeFile.vbs
' Test program for the IncludeFile and ReadConfigFile functions. ' Author: Christian d'Heureuse (www.source-code.biz) ' License: GNU/LGPL (http://www.gnu.org/licenses/lgpl.html) Option Explicit Dim fso: set fso = CreateObject("Scripting.FileSystemObject") ' Includes a file in the global namespace of the current script. ' The file can contain any VBScript source code. ' The path of the file name must be specified relative to the ' directory of the main script file. Private Sub IncludeFile (ByVal RelativeFileName) Dim ScriptDir: ScriptDir = fso.GetParentFolderName(WScript.ScriptFullName) Dim FileName: FileName = fso.BuildPath(ScriptDir,RelativeFileName) IncludeFileAbs FileName End Sub ' Includes a file in the global namespace of the current script. ' The file can contain any VBScript source code. ' The path of the file name must be specified absolute (or ' relative to the current directory). Private Sub IncludeFileAbs (ByVal FileName) Const ForReading = 1 Dim f: set f = fso.OpenTextFile(FileName,ForReading) Dim s: s = f.ReadAll() ExecuteGlobal s End Sub ' Includes the configuration file. ' The configiguration file has the name of the main script ' with the extension ".config". Private Sub ReadConfigFile Dim ConfigFileName: ConfigFileName = fso.GetBaseName(WScript.ScriptName) & ".config" IncludeFile ConfigFileName End Sub ReadConfigFile WScript.Echo "ConfigParm1=" & ConfigParm1 WScript.Echo "ConfigParm2=" & ConfigParm2 Sub1 |
TestIncludeFile.config
' This is a sample configuration file. Const ConfigParm1 = 123 Const ConfigParm2 = "Hello" ' Normally no subroutines would be located within a ' configuration file. ' This is just to demonstrate that it is possible. Sub Sub1() WScript.Echo "Sub1 running" End Sub
|
출처 : http://www.source-code.biz/snippets/vbscript/5.htm