javascript 굿 팁 > script

본문 바로가기
사이트 내 전체검색

script

javascript 굿 팁

페이지 정보

작성자 서방님 댓글 0건 조회 195회 작성일 07-08-08 15:50

본문

 

JavaScript

팝업창의 사용자 접근성 높이기

window.open 을 사용해서 popup window 를 만들때 발생되는 문제를 해결한 방법이다. href="#" onClick="window.open(href, name, property);" 를 쓰게 되면 클릭시 해당 anchor 가 없기 때문에 화면 맨 상단으로 이동하게 된다. href="javascript:void(window.open(href, name, property));" 를 사용하게 되면 새창으로 열거나 북마크를 할 수 없게 된다. 아래 코드를 사용하게 되면 이 문제들이 모두 해결 된다. 최대한 사용자를 배려한 방법이라고 생각 되어 진다. (출처 : http://www.youngpup.net/)

<a href="url" onClick="window.open(this.href, name, property); return false;">Open Popup</a>

ROLLOVER IMAGE

image.gif 의 위에 mouse pointer 가 over 되면 image_on.gif 를 보여주고, out 되면 image.gif 가 보인다.

function menuOn(imgEl) {
	imgEl.src = imgEl.src.replace(".gif", "_on.gif");
}

function menuOut(imgEl) {
	imgEl.src = imgEl.src.replace("_on.gif", ".gif");
}

<img src="image.gif" onmouseover="menuOn(this);" onmouseout="menuOut(this);">

CSS3 Background Image Layering 구현

CSS3 에서 가장 환영할 만한 것이 하나의 element 에 여러개의 background 를 넣을 수 있다는 것이다. 이것이 가능하면 불필요한 markup 을 넣을 필요가 없어지기 때문에 보다 구조적인 문서를 만들기 쉽다. CSS3 의 기능을 완전히 구현한 것은 아니지만 테스트 결과 상당히 유용할 것으로 생각 된다. IE6, Firefox 1.0, Opera7.54 에서 테스트 했음

<!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>CSS3 Background Property</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/* css3 background property implement
 * Author : http://hyeonseok.com
 * Update : http://hyeonseok.com/home/archive_javascript.php#Css3BackgroundImageLayering
 * version : alpha (20050227)
 */
function css3Background(targetElement, backgroundString) {
	if (!targetElement) {
		return false;
	}
	// getStyle script form http://www.quirksmode.org/dom/getstyles.html
	if (window.getComputedStyle) {
		padding = window.getComputedStyle(targetElement,null).getPropertyValue("padding-top");
		padding += " " + window.getComputedStyle(targetElement,null).getPropertyValue("padding-right");
		padding += " " + window.getComputedStyle(targetElement,null).getPropertyValue("padding-bottom");
		padding += " " + window.getComputedStyle(targetElement,null).getPropertyValue("padding-left");
	} else if (targetElement.currentStyle) {
		padding = eval('targetElement.currentStyle.' + "paddingTop");
		padding += " " + eval('targetElement.currentStyle.' + "paddingRight");
		padding += " " + eval('targetElement.currentStyle.' + "paddingBottom");
		padding += " " + eval('targetElement.currentStyle.' + "paddingLeft");
	}
	
	// save content
	originalHTML = targetElement.innerHTML;
	targetElement.innerHTML = "";

	// create div element and layering
	backgroundEach = backgroundString.split(",");
	for (i=0; i<backgroundEach.length; i++) {
		backgroundProperty = backgroundEach[i].replace("background:", "");
	
		el = document.createElement("div");
		if (i==0) {
			targetElement.style.padding = "0";
		}
		el.style.background = backgroundProperty;
		targetElement.appendChild(el);
		targetElement = el;
	}

	targetElement.style.padding = padding;
	targetElement.innerHTML = originalHTML;
	return true;
}
</script>
<style type="text/css">
ul {
	padding: 1em;
	margin: 0.5em;
	padding: 1em 1.5em;
	list-style: none;
	width: 50%;
}
ul li {
	margin: 0.3em 0 0;
	padding: 0.3em 0 0;
	line-height: 1.2em;
	border-top: 1px solid #ddd;
}
ul li:first-child {
	border: none;
}
</style>
</head>

<body>
<h1>CSS3 Background Image Layering 구현</h1>
<h2>사용법</h2>
<ul id="usage">
	<li>함수에 element 와 css3 module 의 background layering 문법을 넘겨주면 됨</li>
	<li>background 속성은 다른 것은 안되고 background short hand 를 콤마로 나열한 방법만 지원됨 (다른 방법은 앞으로도 지원할 생각 없음)</li>
</ul>
<h2>Known defect</h2>
<ul id="defect">
	<li>IE 에서는 p element 에 적용할 경우 "알 수 없는 런타임 에러" 발생. (p 안에 div 가 들어가는 것이 DTD 상에서 오류이기 때문 인 것 같음, 그럼 ul 은? -o-)</li>
	<li>element 의 style 이 유지가 안되기 때문에 element 의 style 을 css 에서 하위 div 까지 중복 선언을 해 주어야 함</li>
	<li>element 안에 div 를 중첩하는 방식이기 때문에 ul, table 등에 사용할 경우는 분명히 문법적으로 오류임. 하지만 markup 이 보존 될 수 있기 때문에 잘 보이기만 하면 별 문제 없을 듯. 이게 싫은 사람은 div, li, td 등과 같이 하위에 div element 를 가질 수 있는 경우에만 사용하면 됨</li>
	<li>IE 에서는 Table element 에 적용했을 경우 정상적으로 나오지 않음 (table 에는 사용하지 마세요.) Firefox 에서는 bg 는 나오지만 어짜피 padding 을 control 할 수 없기 때문에 사용 할 수 없음</li>
	<li>IE 에서는 필수적으로 block model hack 을 사용해야 함 (block 에 dimension 을 주는 방법: width 나 height 둘중의 하나는 block 에 부여를 해야하고 그럴 수 없을 경우 css hack 사용)</li>
	<li>padding 이 이미지에 비해 충분하지 않을 경우 라인이 깨져서 나옴 (당연한 거잖아!)</li>
</ul>
<script type="text/javascript">
css3Background(document.getElementById("usage"), "background: url(bgV.gif) repeat-y top left, background: url(bgV.gif) repeat-y top right, background: url(bgH.gif) repeat-x top left, background: url(bgH.gif) repeat-x bottom left, background: url(bgTL.gif) no-repeat top left, background: url(bgTR.gif) no-repeat top right, background: url(bgBL.gif) no-repeat bottom left, background: url(bgBR.gif) no-repeat bottom right");
css3Background(document.getElementById("defect"), "background: url(bgV.gif) repeat-y top left, background: url(bgV.gif) repeat-y top right, background: url(bgH.gif) repeat-x top left, background: url(bgH.gif) repeat-x bottom left, background: url(bgTL.gif) no-repeat top left, background: url(bgTR.gif) no-repeat top right, background: url(bgBL.gif) no-repeat bottom left, background: url(bgBR.gif) no-repeat bottom right");
</script>
</body>
</html>

선택적으로 className 을 바꾸는 함수

CSS 작업을 하다 보면 서버측에서 class 를 선택적으로 바꿔 주어야 하는 경우가 있다. 예를 들어서 첫번째에는 line 이 없어야 하기 때문에 별도의 class 를 적용한다든가 하는 것들이다. 이러한 것들을 서버 측에서 예외처리를 하여 적용할 수도 있지만, 적용되는 부분이 기능적인 것이 아닌 디자인 적인 요소이기 때문에 클라이언트 측에서 처리를 해줘도 충분하다.

먼저, 첫번째 항목의 class 를 바꾸는 함수.

/* Add First Row Class */
function addFirstRowClass(elId, tagName, searchClass, addClass) {
	var el = document.getElementById(elId).getElementsByTagName(tagName);

	for (i=0; i<el.length; i++) {
		if (el[i].className == searchClass || el[i].className == searchClass + " on") {
			el[i].className = el[i].className + " " + addClass;
			return true;
		}
	}
}

두번째로 짝수 줄의 class 를 바꾸는 함수. 게시판에 짝수 줄에만 컬러가 다른 경우에 사용하면 유용하다.

/* Add Even Row Class */
function addEvenRowClass(elId, tagName, searchClass, addClass) {
	var count = 0;
	var el = document.getElementById(elId).getElementsByTagName(tagName);

for (i=0; i<el.length; i++) {
		if (el[i].className == searchClass) {
			if (count%2) {
				el[i].className = el[i].className + " " + addClass;
			}
			count++;
		}
	}
}

mouse over 시에 작동하는 className 을 정의하는 함수

게시판 같은 곳에서 mouse over 시에 배경 색을 바꾼다든가, 글씨 색을 바꾸는 동작을 줄때, 각 줄에 onmouseover 와 onmouseout 속성을 주어서 제어를 할 수 있다. 하지만 이럴경우 소스코드가 복잡해 지고 덩치가 커지게 된다. 또한 이러한 동작은 디자인적인 요소가 강하기 때문에 javascript 로 클라이언트 환경에서 처리를 해주는 것이 보다 효율적이다.

changeOverRowClass 함수는 초기화 함수이다. 해당 element ID 와 tagName, 대상이 되는 class 를 지정해서 선택적으로 changeOverRowClassOver 함수와 changeOverRowClassOut 를 적용 할 수 있다.

/* Change Over Row Class */
function changeOverRowClass(elId, tagName, searchClass) {
	var el = document.getElementById(elId).getElementsByTagName(tagName);

	for (i=0; i<el.length; i++) {
		if (el[i].className == searchClass || el[i].className == searchClass + " on") {
			el[i].onmouseover = changeOverRowClassOver;
			el[i].onmouseout = changeOverRowClassOut;
		}
	}
}
function changeOverRowClassOver() {
	if (this.className == "") {
		this.className = this.className + " on";
	} else {
		this.className = "on";
	}
}
function changeOverRowClassOut() {
	if (this.className == "on") {
		this.className = "";
	} else {
		this.className = this.className.replace(" on", "");
	}
}

Definition List Toggle

FAQ 리스트 같은 곳에 사용하기 편한 toggle list 이다.Definition List 에 style 을 적용한 후 initToggleDefList(elementId); 로 활성화만 시켜주면 간단히 사용할 수 있게 수정했다.

<!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=utf-8" />
<title>Definition List Toggle</title>
<script type="text/javascript">
/* definition list toggle */
function initToggleDefList(listEl) {
	listEl.currentItem = false;
	listEl.dtList = listEl.getElementsByTagName("dt");
	listEl.ddList = listEl.getElementsByTagName("dd");

	for (i=0; i<listEl.getElementsByTagName("dt").length; i++) {
		listEl.dtList.item(i).dlEl = listEl;
		listEl.dtList.item(i).listNum = i;
		listEl.dtList.item(i).onclick = toggleDefinitionList;
	}
}
function toggleDefinitionList() {
	if (this.dlEl.dtList.item(this.dlEl.currentItem) && this.dlEl.ddList.item(this.dlEl.currentItem) && this.dlEl.currentItem != this.listNum) {
		this.dlEl.dtList.item(this.dlEl.currentItem).className = null;
		this.dlEl.ddList.item(this.dlEl.currentItem).className = null;
	}

	if (this.dlEl.ddList.item(this.listNum).className == "on") {
		this.dlEl.dtList.item(this.listNum).className = null;
		this.dlEl.ddList.item(this.listNum).className = null;
	} else {
		this.dlEl.dtList.item(this.listNum).className = "on";
		this.dlEl.ddList.item(this.listNum).className = "on";
	}

	this.dlEl.currentItem = this.listNum;
}
</script>
<style type="text/css">
#faq-list {
	width: 500px;
}
#faq-list dt {
	border-bottom: 1px solid #ccc;
	padding: 0.5em;
	cursor: pointer;
}
#faq-list dt:hover {
	background: #fafafa;
}
#faq-list dd {
	border: 1px solid #ccc;
	padding: 0.5em;
	margin: 1em;
	display: none;
}
#faq-list dd.on {
	display: block;
}
</style>
</head>

<body>
<h1>Faq For Publish</h1>
<dl id="faq-list">
	<dt>HTML 은 무엇인가요?</dt>
	<dd>HTML 은 <a href="http://w3c.org/MarkUp/">HyperText Mark up Language</a> 로서 구조적은 문서를 제작할때 사용하는 markup 언어 입니다.</dd>
	<dt>CSS 는 무엇인가요?</dt>
	<dd><a href="http://w3c.org/Style/CSS/">Cascading Style Sheet</a> 의 약자로서 HTML, XHTML, XML 등과 같은 구조를 나타낸 문서의 표현 형태를 정의하는 방법입니다.</dd>
	<dt>W3C 는 무엇인가요?</dt>
	<dd><a href="http://w3c.org">World Wide Web Consrotium</a> 이라는 비 영리 단체로서 인터넷을 발명한 <a href="http://en.wikipedia.org/wiki/Tim_Berners-Lee">Tim Berners-Lee</a> 가 만든 단체 입니다. HTML, CSS, XHTML, XML 등 많은 웹표준을 만들었고 W3C 산하의 많은 단체에서 웹의 보편성을 위해서 많은 노력을 하고 있습니다.</dd>
	<dt>XHTML 은 무엇인가요?</dt>
	<dd>웹이 XML 로 넘어가는 과도기적인 형태의 문서 입니다. 간단하게 말하면, HTML 의 DTD 를 많이 따르면서 XML 의 문법에 기초한 Mark up 언어 입니다.</dd>
	<dt>ECMA Script 는 무엇인가요?</dt>
	<dd><a href="http://www.ecma-international.org">ECMA International</a> 에서 만은 <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">Script Language 표준</a>입니다. 쉽게 생각해서 Javascript 표준이라고 생각 하면 됩니다. MS Internet Explorer, Mozilla, Mozilla Firefox, Opera 등 거의 대부분의 브라우져에서 채택하고 있는 Script 언어 표준 입니다.</dd>
</dl><!-- end of #faq-list -->
<script type="text/javascript">
initToggleDefList(document.getElementById("faq-list"));
</script>
</body>
</html>

컨텐츠 Tab 형식으로 보여주기

cjchina.net 에서 사용했던 script. 아직 일반화 작업이 안되었음

[style]
#tabMenu {
	background: url("/CJGC002/img/tabMenu.gif") no-repeat bottom;
	width: 395px;
	height: 44px;
	margin-top: 25px;
}
#tabCont {
	background: url("/CJGC002/img/tabCont.gif") repeat-y;
	width: 395px;
	height: auto;
}
#tabCont div.bottom {
	background: url("/CJGC002/img/tabContBtm.gif") repeat-y;
	width: 395px;
	height: 20px;
}
#tabCont div.cont {
	padding: 14px 0 10px;
	margin: 0 22px;
	width: 351px;
	display: none;
}
#tabCont div.cont div.numText {
	text-indent: -1.2em;
	padding-left: 1.2em;
}

[javascrpit]
function menuOver() {
	this.src = this.src.replace(".gif", "_on.gif");
}
function menuOut() {
	this.src = this.src.replace("_on.gif", ".gif");
}

var currentProdCont;
function initProdContent() {
	menuEl = document.getElementById("tabMenu").getElementsByTagName("img");
	for (i = 0; i < menuEl.length; i++) {
		menuEl[i].onmouseover = menuOver;
		menuEl[i].onmouseout = menuOut;
	}
	viewProdContent("1");
}
function viewProdContent(contNumber) {
	if (currentProdCont && currentProdCont != contNumber) {
		document.getElementById("cont" + currentProdCont).style.display = "none";
		lastMenuEl = document.getElementById("tabMenu" + currentProdCont);
		lastMenuEl.src = lastMenuEl.src.replace("_on.gif", ".gif");
		lastMenuEl.onmouseover = menuOver;
		lastMenuEl.onmouseout = menuOut;
	}

	document.getElementById("cont" + contNumber).style.display = "block";
	menuEl = document.getElementById("tabMenu" + contNumber);
	if (!currentProdCont) {
		menuEl.src = menuEl.src.replace(".gif", "_on.gif");
	}
	menuEl.onmouseover = null;
	menuEl.onmouseout = null;
	
	currentProdCont = contNumber;
}

[HTML]
<div id="tabMenu">
	<a href="javascript:viewProdContent('1')" onfocus="this.blur()"><img src="img/tabMenu01.gif" id="tabMenu1" alt="?品特点"></a>
	<a href="javascript:viewProdContent('2')" onfocus="this.blur()"><img src="img/tabMenu02.gif" id="tabMenu2" alt="?品用途"></a>
	<a href="javascript:viewProdContent('3')" onfocus="this.blur()"><img src="img/tabMenu03.gif" id="tabMenu3" alt="使用指引"></a><br>
</div>
<div id="tabCont">
	<div id="cont1" class="cont" style="height: 115px;">
		<div class="numText">1. 天然----大自然的味道</div>

		<div class="numText">2. 牛肉味?郁、醇厚、?香,胃口大?</div>
		<div class="numText">3. ??健康每一餐</div>
		<div class="numText">4. ?松方便、省?省力</div>
	</div>
	<div class="designBlock"> </div>
	<div id="cont2" class="cont" style="height: 115px;">
		适用于各?烹?:煎、炒、烹、炸、?、拌、?、蒸均可。
		<div class="numText">1. 在烹?炒菜?,替代味精使用,味道更?、原味更醇;</div>

		<div class="numText">2. 用于??、火?等各式?中?味,味道更?、更持久。且可?松享用需???方可熬成的上?;</div>
		<div class="numText">3. 在制作各?面?、点心、水?、包子、???,加入适量?味,味道?又香。</div>
	</div>
	<div class="designBlock"> </div>
	<div id="cont3" class="cont" style="height: 115px;">
		使用?,最好先加入大喜大牛肉粉提?,然后再依?人口味酌量添加???整咸淡。 ( 因本品含有少量?和?油,?影?咸度)<br>
		<br>

		做?:1升水放15g,供4-5人用<br>
		炒菜:1? ( 4人? ) 放5g<br>
	</div>
	<div class="designBlock bottom"> </div>
</div>
<script type="text/javascript">
initProdContent('1');
</script>

컨텐츠 슬라이드

컨텐츠 영역의 height 가 정해져 있는 경우, 컨텐츠 표현을 위해서 scroll 을 이용하는 경우가 있다. 이러한 컨텐츠를 스크롤이 아닌 좌우 슬라이드로 보여주는 효과이다.

slideContent 라는 block 이 페이지의 단위이고 이 단위 갯수 만큼 페이징이 이루어 진다.
버튼을 이미지로 사용하는 경우 javascript 의 isImageBtn 을 true 로 하시고 이미지를 넣으면 되고 dimmed 된 이미지의 파일명은 _off 를 붙이면 된다.
페이지의 디자인은 CSS 를 수정하면 되고 content 의 폭인 contentWidth (컨텐츠간의 여백포함) 를 같이 조절해 주면 된다.

[HTML]
<div id="slideContentContainer">
	<div id="slideContent">
		<div class="slideContent">Firefox is a browser built for speed and security, and getting rave reviews from the likes of PC World, PC Magazine, and USA Today -- even Microsoft's security program manager runs Firefox! This free and fast little browser can block unwanted popups, and keep your desktop clutter-free with tabbed browsing. It's definitely more secure than Internet Explorer, and a cinch to install:</div>
		<div class="slideContent">1. Browse to http://www.mozilla.org/firefox/.<br>
			2. Choose the download link appropriate for the operating system on which you'll be running Firefox -- Windows, Linux, or Mac OS X.<br>
			3. Save the file to your desktop.<br>
		</div>
		<div class="slideContent"> 4. Double-click on the file you just downloaded to start the installation wizard.<br>
			5. Click “Next” on each step of the wizard until the program is installed.<br>
			6. If you like, you can set Firefox to be your default browser, instead of Internet Explorer.<br>
			7. Start up Firefox, and browse happy.<br>
		</div>
	</div>
</div>
<div id="slideBtnSet">
	<span id="prevBtn">prev</span> <span id="nextBtn">next</span>
	<!--img id="prevBtn" src="btnPrev.gif" alt="prev"> <img id="nextBtn" src="btnNext.gif" alt="next"><br-->
</div>
<script type="text/javascript">
initScrollContent();
</script>

[STYLE]
#slideContentContainer {
	position: relative;
	width: 400px;
	height: 200px;
	border: 2px solid #eee;
	overflow: hidden;
}
#slideContent {
	position: absolute;
}
#slideContent div.slideContent {
	position: absolute;
	width: 380px;
	padding: 10px;
}
#slideBtnSet {
	width: 380px;
	padding: 10px;
	text-align: right;
}
#slideBtnSet *.on {
	color: #000;
	cursor: pointer;
}
#slideBtnSet *.off {
	color: #aaa;
	cursor: default;
}

[javascript]
/* Slide Content */
var currentContentPage = 1;
var contentElCount = 0;
var content_x = 0;
var slideContentTo = 0;
var contentWidth = 400;
var isImageBtn = false;

function initScrollContent(initCont) {
	cont = document.getElementById("slideContent").getElementsByTagName("div");

	for (i=0; i<cont.length; i++) {
		if (cont[i].className == "slideContent") {
			contentElCount++;
			cont[i].style.left = contentWidth * (contentElCount - 1) + "px";
		}
	}

	setSlideBtn();
}
function setSlideBtn() {
	if (parseInt(currentContentPage) == 1) {
		setPrevBtn("off");
		setNextBtn("on");
	} else if (parseInt(currentContentPage) == contentElCount) {
		setPrevBtn("on");
		setNextBtn("off");
	} else {
		setPrevBtn("on");
		setNextBtn("on");
	}
}
function setPrevBtn(condition) {
	var prevBtn = document.getElementById("prevBtn");

	if (condition == "on") {
		prevBtn.onclick = viewPrev;
		if (isImageBtn) prevBtn.src = prevBtn.src.replace("_off.gif", ".gif");
		prevBtn.className = "on";
	} else {
		prevBtn.onclick = "";
		if (isImageBtn) prevBtn.src = prevBtn.src.replace(".gif", "_off.gif");
		prevBtn.className = "off";
	}
}
function setNextBtn(condition) {
	var nextBtn = document.getElementById("nextBtn");

	if (condition == "on") {
		nextBtn.onclick = viewNext;
		if (isImageBtn) nextBtn.src = nextBtn.src.replace("_off.gif", ".gif");
		nextBtn.className = "on";
	} else {
		nextBtn.onclick = "";
		if (isImageBtn) nextBtn.src = nextBtn.src.replace(".gif", "_off.gif");
		nextBtn.className = "off";
	}
}
function viewPrev() {
	slideContentTo += contentWidth;
	currentContentPage = parseInt(currentContentPage) - 1;
	setSlideBtn();
	startScroll();
}
function viewNext() {
	slideContentTo -= contentWidth;
	currentContentPage = parseInt(currentContentPage) + 1;
	setSlideBtn();
	startScroll();
}
function startScroll() {
	setTimeout("slideContent()", 10);
}
function slideContent() {
	if (Math.abs(content_x - slideContentTo) > 1) {
		content_x += (slideContentTo - content_x) * .15;
		document.getElementById("slideContent").style.left = content_x + "px";
		startScroll();
	} else {
		content_x = slideContentTo;
		document.getElementById("slideContent").style.left = content_x + "px";
	}
}

object 로 불러온 flash 무비를 IE 용 Active-x 로 바꾸기

IE 는 object 를 불러오는 방식을 windows 의 active-x 를 사용하기 때문에 타 플랫폼과는 호환이 안되는 치명적인 단점을 가지고 있다. macromedia 의 flash 무비 로드 방식으로 해결 할 수 있지만 이 방법 자체가 W3C 에서 제안하는 object 사용방법은 아니다.

이 방법은 표준에 의거해서 object 를 사용해 flash 를 불러오고 표준을 정상적으로 처리 하지 않는 IE 에서는 javascript 를 이용해서 IE 의 Active-x 를 불러오는 방식을 적용하는 것이다.

[script]
function convertFlashToActiveX(objParent) {
	// convert XHTML flash object to IE active-x control
	if(window.ActiveXObject) {
		flashObj = objParent.getElementsByTagName("object").item(0);

		movieUrl = flashObj.getAttribute("data");
		movieWidth = flashObj.getAttribute("width");
		movieHeight = flashObj.getAttribute("height");

		movieParam = "";	// IE cannot load param element by innerHTML
		alert(movieParam);
		paramEl = flashObj.getElementsByTagName("param");
		for (i=0; i<paramEl.length; i++) {
			movieParam += "<param name="" + paramEl.item(i).getAttribute("name") + "" value="" + paramEl.item(i).getAttribute("value") + "" />n";
		}

		// out put
		objParent.innerHTML = "<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="" + movieWidth + "" height="" + movieHeight + "">n" + movieParam + "n</object>n";
	}
}
[style]
* html object.ie-active-x-bug {
	display: none;
}
[HTML]
<!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=utf-8" />
<title>Convert Flash plug-in to Active-x</title>
</head>
<body>
<div id="myFlash"> 
	<object type="application/x-shockwave-flash" data="myFlash.swf" width="900" height="189" class="ie-active-x-bug">
		<param name="movie" value="myFlash.swf" />
		<param name="allowScriptAccess" value="sameDomain" />
	</object>
</div>
<script type="text/javascript">
convertFlashToActiveX(document.getElementById("myFlash"));
</script>
</body>
</html>

object.ie-active-x-bug 는 IE 가 object 를 인식하지 못해서 화면에 깨진 이미지 같은 것이 나오는 것을 방지하기 위한 class 이다.

쿠키를 이용해서 팝업 윈도우 제어

창을 여는 화면의 함수 선언과 창 띄우기

function getCookie(name) { 
	var Found ;
	Found = false ;
	var start, end ;
	var i = 0 ;

	// cookie 문자열 전체를 검색
	while (i <= document.cookie.length) { 
		start = i ;
		end = start + name.length ;

		// name과 동일한 문자가 있다면 
		if(document.cookie.substring(start, end) == name) { 
			//Found = true ;
				return true;
			break ;
		} 
		i++ ;
	} 

	// name 문자열을 cookie에서 찾았다면 
	if(Found == true) { 
		start = end + 1 ;
		end = document.cookie.indexOf(';', start) ;

		// 마지막 부분이라는 것을 의미(마지막에는 ";"가 없다) 
		if(end < start) 
			end = document.cookie.length ;

		// name에 해당하는 value값을 추출하여 리턴한다. 
		return document.cookie.substring(start, end) ;
	} 

	// 찾지 못했다면 
	return '' ;
}

// 이벤트 페이지 popup
if (getCookie('cookie_name') != true) {
	window.open ('popup.html', 'popup_window_name', 'left=0, top=0, toolbar=no, status=no, width=400, height=500, directories=no, scrollbars=1, location=no, resizable=no, menubar=no');
}

팝업창에서의 함수선언

function controlCookie(elemnt) {
	if (elemnt.checked) {
		//체크 박스를 선택했을 경우 쿠키 생성 함수 호출
		setCookie("cookie_name","true", 1);
	}
	else {
		//체크 박스를 해제했을 경우 쿠키 소멸 함수 호출
		clearCookie("cookie_name")
	}
	return
}

//쿠키 생성 함수
function setCookie(name, value, expire) {
	var expire_date = new Date()
	expire_date = new Date(expire_date.getTime() + 60*60*24*1000)
	document.cookie = name + "=" + escape(value) + "; expires=" + expire_date.toGMTString() +"; path=/";
	self.close();
}

//쿠키 소멸 함수
function clearCookie(name) {
	var today = new Date()
	//어제 날짜를 쿠키 소멸 날짜로 설정한다.
	var expire_date = new Date(today.getTime() - 60*60*24*1000)
	document.cookie = name + "= " + "; expires=" + expire_date.toGMTString()
}

팝업창에서의 버튼

<div align="center">
	<input type="checkbox" name="checkbox" onclick="controlCookie(this)">
	오늘 하룻동안 이창을 띄우지 않습니다.
</div>

cookie_name 과 popup window file name, popup window name 을 수정해주면 된다.

Iframe 크기 맞추기

embeded document 의 마지막 부분에서 iframe size 를 조정해 준다. offsetWidth나 offsetHeight 는 DOM 표준 속성은 아니다. 하지만 IE 와 Moz 둘다 정상적으로 작동을 한다.

parent.document.getElementById("ifrmeId").style.height = document.getElementById("embededObject").offsetHeight;
parent.document.getElementById("ifrmeId").style.width = document.getElementById("embededObject").offsetWidth;

창을 작업표시줄로 내리기 (window only)

이것은 Javascript 는 아니고, active-x control 을 이용하여 창을 강제로 내리는 것이다. 따라서 Windows 에서만 작동하게 된다.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Minimize Window</title>
<META http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<SCRIPT type="text/JavaScript">
function mini() {
	minobj.Click();
}
</SCRIPT>
</head>

<body>
<span onclick="window.mini()" style="cursor: pointer;">Minimize</span>
<OBJECT id=minobj type="application/x-oleobject" classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11" codebase="hhctrl.ocx#Version=4,72,8252,0">
	<PARAM name="Command" value="minimize">
</OBJECT>
</body>
</html>

마우스와 키보드 사용 못하게 하는 방법

사용자 접근성에 있어서는 최악이고 내가 이것을 사용할 일은 없겠지만, 혹시 "갑" 이 요청을 하면...어쩔 수 없지...

<body oncontextmenu="return false" ondragstart="return false" onselectstart="return false" onkeypress="CheckKeyPress();">

function click() {
	if ((event.button==2) || (event.button==3)) {
		alert('오른쪽 버튼은 사용할수 없습니다.');
		return false;
	}
}

document.onmousedown=click;
//키입력체크
document.onkeydown = CheckKeyPress;
document.onkeyup = CheckKeyPress;

function CheckKeyPress() {
	//키입력
	ekey = event.keyCode;
	//리턴
	if(ekey == 38 || ekey == 40 || ekey == 44 || ekey == 78 || ekey == 112 || ekey ==17 || ekey == 18 || ekey == 25 || ekey == 122) {
		alert("이 특수키는 사용할수 없습니다.");
		event.keyCode = 0;
		return false;
	}
}

일정기간만 팝업창 열기 (ASP)

기간내에 popup window 를 여는 script 이다. 엄밀히 말하면 asp 난을 만들고 이 내용을 넣어야 하겠지만 업무상 필요한 내용이래서 그냥 추가...

<%
dim todayYear, todayMonth, todayDay

todayYear = Year(Now)
todayMonth = Month(Now)
todayDay = Day(Now)

if (todayYear = 2003 and todayMonth = 9 and todayDay >= 19) and (todayYear = 2003 and todayMonth = 9 and todayDay <= 30) then
%>
<script type="text/javascript">
window.open('popup.html','popup','scrollbars=yes,resizable=yes,width=620,height=500,left=0, top=0')
</script>
<%
end if
%>

댓글목록

등록된 댓글이 없습니다.

Total 846건 37 페이지
게시물 검색

회원로그인

접속자집계

오늘
65
어제
302
최대
1,347
전체
155,126
Latest Crypto Fear & Greed Index

그누보드5
Copyright © 서방님.kr All rights reserved.