------------------------------------------------------------ 제작자에게 문의없이 소스 공개 합니다. 문제될시 삭제 토록 하겠습니다. 1. htc확장자 인 파일을 만들어둔다. ex)select.htc 파일안에 삽입될 내용 <public:component URN="lyrSelectBox" />
<public:attach event="ondocumentready" handler="initializeSelectBox" />
<public:attach event="onpropertychange" handler="eventChangeProperty" />
<public:attach event="" for="document" handler="eventMouseDown" />
<public:attach event="onkeydown" for="document" handler="eventKeyDown" />
<public:property name="setColor" put="setupColor" />
<public:property name="setImage" put="setupImage" />
<public:property name="setDisplayCount" put="setupDisplayCount" />
<public:method name="reInitializeSelectBox" /> <script language="JScript">
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// 스크립트명 - SelectBox -> 드롭다운 메뉴 변환 HTC
// 설 명 - SelectBox 폼필드를 레이어 형태의 드롭다운 메뉴로 자동 변경
// 제 작 자 - TarauS (taraus@naver.com)
// 메 신 져 - MSN Messenger -> taraus@hanmail.net
//
// * 스크립트 목적
// - 기존의 셀렉트박스를 스타일의 적용이 가능한 레이어 형태(실제로는 테이블과 Popup Object)로 자동 변환
//
// * 주요 기능 및 특징
// - 기존 셀렉트박스 태그의 수정 없이 스타일 시트에 정의하는 것만으로 모든 셀렉트박스 변환 가능
// - 셀렉트박스를 기준으로 아래위의 여백을 비교하여 옵션 항목 창의 출력 방향 결정
// - 기존 셀렉트박스처럼 변환된 셀렉트박스도 포커스를 가질 수 있음
// document.getElementById('SelectBox_Name').focus();
// - 변환된 셀렉트박스가 포커스를 가지고 있을 경우 휠을 움직이거나 키보드의 Home, End, Page Up, Page Down,
// Up Arrow, Down Arrow 등을 누름에 따라 값의 변경이 가능
// 또한 열려진 옵션 항목 창에서도 가능함
// - 위의 이벤트 시에 문서의 스크롤을 제어하여 문서의 움직임이 없음
// - 아이프레임 및 프레임에 삽입된 상황에서도 프레임에 영향을 받지 않고 정상적으로 출력
// (Layer가 아닌 Popup Object를 이용)
// - 셀렉트박스의 항목이 동적으로 변경할 경우를 위한 메소드 제공
// document.getElementById("SelectBox_Name").reInitializeSelectBox();
// - 옵션 항목 창에 출력될 항목의 갯수를 지정(setDisplayCount() 메소드 이용)할 수 있으며 항목이 출력될
// 갯수보다 많을 경우 자동으로 스크롤바 생성 (기본값은 10)
// - 셀렉트박스 및 옵션 항목에 대해 툴팁 메세지 설정 가능
// - 특정 셀렉트박스의 색상 및 화살표 이미지 변경 가능
// - 변환된 레이어를 텍스트처럼 취급 (연속적인 출력이 가능, 하단 여백 없음)
// - HTC 가 지원되는 브라우져에서만 변환 (HTC는 5.0 이상에서 가능하나 createPopup() 메소드가 5.5부터
// 지원되어 IE 5.5 이상에서만 변환)
// - 옵션 항목 창 출력시 일시적으로 문서가 길어져 스크롤바가 출력되는 일이 없음
// - 셀렉트박스가 disabled 상태일 경우 처리
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////// // 변수 선언
var objSelectBox = this;
var widthObject, widthObjectOriginal, heightObject;
var tblTitle, tbdTitle, trTitle, tdTitle;
var objItemWindow, objItemDocument, objItemBody, objItemEvent;
var tblItem, tbdItem, trItem, tdItem;
var leftObject, heightItemWindow, heightTitleTable;
var countMaxItem = 5;
var countItem = this.length;
var is_open = false;
var is_loaded = false;
var focusElement; // 기본 색상 및 글자 설정
var normal_bgcolor = "#FFFFFF";
var normal_color = "#545454";
var disabled_color = "#C0C0C0";
var active_bgcolor = "#F5F5F5";
var active_color = "#000000";
var normal_border_tag = "1 solid #CCCCCC";
var active_border_tag = "1 solid #CCCCCC";
var font_tag = "normal 12px 굴림";
var arrow_image = ""; //-------- 프로퍼티 설정 함수
// 프로퍼티로 색상을 설정시에 색상 관련 변수 변경
function setupColor(color_list){
var color_array = color_list.split(",");
var color = new Array(); for(i=0; i<color_array.length; i++){
color[i] = color_array[i];
} if(color[0]) normal_color = color[0];
if(color[1]) normal_bgcolor = color[1];
if(color[2]) active_color = color[2];
if(color[3]) active_bgcolor = color[3];
if(color[4]) normal_border_tag = "1 solid "+color[4];
if(color[5]) active_border_tag = "1 solid "+color[5];
} // 프로퍼티로 화살표 이미지를 설정시에 화살표 이미지를 변경
function setupImage(image_file){
if(image_file) arrow_image = image_file;
} // 옵션 항목의 최대 출력 갯수 변경
function setupDisplayCount(max_count){
if(max_count) countMaxItem = max_count;
}
//-------- 문서 스크롤 관련 함수
// 문서의 스크롤링을 불가능하도록 설정
function disableScroll(){
window.execScript("document. = function(){return false;}");
window.execScript("document.onkeydown = function(){return false;}");
} // 문서의 스크롤링을 가능하도록 설정
function enableScroll(){
window.execScript("document. = function(){return true;}");
window.execScript("document.onkeydown = function(){return true;}");
} //-------- 이벤트 관련 함수
// 타이틀 출력 테이블 Mouse Over Event
function eventMouseOverTT(){
if(!objSelectBox.disabled){
tblTitle.style.border = active_border_tag;
imgArrow.style.filter = '';
}
} // 타이틀 출력 테이블 Mouse Out Event
function eventMouseOutTT(){
tblTitle.style.border = normal_border_tag;
imgArrow.style.filter = 'gray()';
} // 아이템 출력 테이블 Mouse Over Event
function eventMouseOverIT(idx){
removeItemStyle();
tdItem[idx].style.color = active_color;
tdItem[idx].style.background = active_bgcolor;
focusElement = tdItem[idx];
} // on MouseDown Event
function eventMouseDown(){
if(is_open) changeItemWindowDisplay();
} // 셀렉트박스 Focus Event
function eventFocusSB(){
tdTitle_sv.innerHTML = objSelectBox.options[selectedIndex].text;
tdTitle_sv.style.color = active_color;
tdTitle_sv.style.background = active_bgcolor;
} // 셀렉트박스 Blur Event
function eventBlurSB(){
tdTitle_sv.style.color = normal_color;
tdTitle_sv.style.background = normal_bgcolor;
} // 셀렉트박스 Key Down Event
function eventKeyDownSB(){
var keycode = window.event.keyCode ? window.event.keyCode : window.event.which ? window.event.which : window.event.charCode;
if(is_open && focusElement && keycode == 13){
nowIndex = focusElement.getAttribute("key");
changeSelectBoxValue(nowIndex);
}
} // on KeyDown 이벤트 처리
function eventKeyDown(){
var keycode = window.event.keyCode ? window.event.keyCode : window.event.which ? window.event.which : window.event.charCode;
var eventElement = window.event.srcElement
// 셀렉트박스가 포커스를 가지고 있을 때 스페이스바를 이용하여 옵션 항목 창을 보이고 사라지게 하는 부분
// 현재는 옵션 항목 창이 열렸을 때의 이벤트 객체 문제와 옵션 항목 창 출력 방향 문제로 임시로 주석 처리함
//if(keycode == 32 && eventElement.type == "select-one" && eventElement.name == this.name){
// changeItemWindowDisplay();
//} if(is_open && focusElement){
var firstIndex = 0;
var lastIndex = countItem - 1;
var nowIndex = objSelectBox.selectedIndex;
var tmpIndex = 0;
var change_value_check = false;
nowIndex = focusElement.getAttribute("key"); if(window.event.altKey) closeItemWindow();
if(keycode == 38){ // 위쪽 방향키를 눌렀을 때
tmpIndex = nowIndex - 1;
if(tmpIndex < firstIndex) tmpIndex = firstIndex;
selectIndex = tmpIndex;
change_value_check = true;
}else if(keycode == 40){ // 아래쪽 방향키를 눌렀을 때
tmpIndex = nowIndex + 1;
if(tmpIndex > lastIndex) tmpIndex = lastIndex;
selectIndex = tmpIndex;
change_value_check = true;
}else if(keycode == 33){ // Page Up 키를 눌렀을 때
tmpIndex = nowIndex - countMaxItem - 1;
if(tmpIndex < firstIndex) tmpIndex = firstIndex;
selectIndex = tmpIndex;
change_value_check = true;
}else if(keycode == 34){ // Page Down키를 눌렀을 때
tmpIndex = nowIndex + countMaxItem - 1;
if(tmpIndex > lastIndex) tmpIndex = lastIndex;
selectIndex = tmpIndex;
change_value_check = true;
}else if(keycode == 36){ // Home 키를 눌렀을 때
selectIndex = firstIndex;
change_value_check = true;
}else if(keycode == 35){ // End 키를 눌렀을 때
selectIndex = lastIndex;
change_value_check = true;
}else if(keycode == 13){
if(focusElement != null) changeSelectBoxValue(nowIndex);
} if(change_value_check){
removeItemStyle();
tdItem[selectIndex].style.color = active_color;
tdItem[selectIndex].style.background = active_bgcolor;
objItemBody.scrollTop = selectIndex * 20;
focusElement = tdItem[selectIndex];
}
}
} // on MouseWheel 이벤트 처리 (현재 미작동)
// on MouseWheel 이벤트가 IE 6.0부터 지원되는 점과 팝업창의 이벤트 객체 제어 문제로 기능 삭제
function eventMouseWheel(){
if(is_open){
if(!focusElement) idx = objSelectBox.selectedIndex;
else idx = focusElement.key; for(i=0; i<window.event.wheelDelta; i+=120) idx--;
for(i=0; i>window.event.wheelDelta; i-=120) idx++;
idx = Math.max(idx, 0);
idx = Math.min(idx, countItem - 1); removeItemStyle();
tdItem[idx].style.color = active_color;
tdItem[idx].style.background = active_bgcolor;
objItemBody.scrollTop = idx * 20;
focusElement = tdItem[idx];
}
} // SelectBox Change Property Event
function eventChangeProperty(){
if(window.event.type == "propertychange" && window.event.propertyName == "selectedIndex"){
tdTitle_sv.innerHTML = objSelectBox.options[objSelectBox.selectedIndex].text;
if(objSelectBox.onchange != null) objSelectBox.onchange();
}
} //-------- 옵션 항목 창 관련 함수
// 옵션 항목 창의 출력 상태에 따라 보여주거나 닫음
function changeItemWindowDisplay(){
if(is_open == false){
if(countItem && !objSelectBox.disabled) openItemWindow()
}else{
closeItemWindow();
}
} // 옵션 항목 창 열기
function openItemWindow(){
eventBlurSB(); heightScreen = window.screen.height;
spaceDown = heightScreen - window.event.screenY - heightTitleTable;
spaceUp = heightScreen - spaceDown; // Item Window를 위로 출력
if((objSelectBox.length <= countMaxItem && (objSelectBox.length * 20 + 4) > spaceDown) || (objSelectBox.length > countMaxItem && spaceDown < (countMaxItem * 20 + 4))){
objItemWindow.show(0,(0-heightItemWindow),widthObject,heightItemWindow,tblTitle);
// Item Window를 아래로 출력
}else{
objItemWindow.show(0,heightTitleTable,widthObject,heightItemWindow,tblTitle);
} var idx = objSelectBox.selectedIndex;
tdItem[idx].style.color = active_color;
tdItem[idx].style.background = active_bgcolor;
objItemBody.scrollTop = idx * 20;
focusElement = tdItem[idx];
disableScroll();
is_open = true;
} // 옵션 항목 창 닫기
function closeItemWindow(){
objItemWindow.hide();
removeItemStyle();
enableScroll();
objSelectBox.focus();
is_open = false;
}
//-------- 환경 설정 및 변환 관련 함수
// 초기화 함수
function initializeSelectBox(){
var browser_version = new Number(((window.navigator.appVersion.split('; '))[1].split(' '))[1]); if(this.type != "select-one" || this.size != 0){
return;
}else if(navigator.appName != "Microsoft Internet Explorer" || browser_version < 5.5){
return;
}else{
objSelectBox.attachEvent("",eventFocusSB);
objSelectBox.attachEvent("",eventBlurSB); initializeBasicInformation();
initializeTitleTable();
if(countItem){
initializeItemWindow();
initializeItemTable();
}
is_loaded = true;
}
} // 동적으로 셀렉트박스의 항목이 변경될 경우 다시 변환할 수 있는 메소드
function reInitializeSelectBox(){
countItem = objSelectBox.length;
tblTitle.removeNode(true);
initializeBasicInformation();
initializeTitleTable();
initializeItemWindow();
initializeItemTable();
} // 셀렉트 박스를 레이어 형태로 변형하기 위한 기본 정보 설정
function initializeBasicInformation(){
// style.width 속성을 사용자가 설정한 경우 사용자 설정값으로 넓이를 설정 함
// this.offsetWidth 속성을 가끔 불러오지 못하는 경우가 있어 이럴 경우 이전 버전에서
// 사용하던 getStringPixelWidth()함수를 이용하여 넓이를 직접 계산 후 설정 함
if(is_loaded == false && objSelectBox.style.width){
widthObject = parseInt(objSelectBox.style.width);
widthObjectOriginal = widthObject;
}else if(is_loaded == false && objSelectBox.offsetWidth){
widthObject = objSelectBox.offsetWidth;
}else{
var lengthMax = 0;
if(countItem){
for(i=0; i<countItem; i++){
lengthItem = getStringLength(objSelectBox.options[i].text);
if(lengthMax < lengthItem){
lengthMax = lengthItem;
stringMax = objSelectBox.options[i].text;
}
}
widthObject = getStringPixelWidth(stringMax) + 12 + 12 + 2;
}
}
objSelectBox.style.width = "0px"; heightTitleTable = 22;
if(countItem < countMaxItem){
heightItemWindow = countItem * 20 + 2 + 2;
widthItemTable = widthObject - 2;
}else{
heightItemWindow = countMaxItem * 20 + 2 + 2;
widthItemTable = widthObject - 18;
}
heightObject = heightTitleTable + heightItemWindow;
} // 타이틀 테이블 설정
function initializeTitleTable(){
// 옵션 항목이 있을 경우 선택된 값을 변환된 셀렉트박스의 기본값으로 설정
if(countItem){
if(!objSelectBox.selectedIndex) objSelectBox.selectedIndex = 0;
var textDefault = objSelectBox.options[objSelectBox.selectedIndex].text;
// 옵션 항목이 없을 경우 기본 사이즈를 60px로 설정
}else{
var textDefault = "";
widthObject=60;
}
var tooltip = objSelectBox.tooltip; // 타이틀 테이블 생성 및 셋팅
tblTitle = document.createElement("TABLE");
tblTitle.border = 0;
tblTitle.cellSpacing = 0;
tblTitle.cellPadding = 0;
tblTitle.style.width = widthObject;
tblTitle.style.height = heightTitleTable;
tblTitle.style.color = normal_color;
tblTitle.style.background = normal_bgcolor;
tblTitle.style.border = normal_border_tag;
tblTitle.style.display = "inline";
tblTitle.style.verticalAlign = "bottom";
tblTitle. = eventMouseOverTT;
tblTitle. = eventMouseOutTT;
if(tooltip != null) tblTitle.title = tooltip; tbdTitle = document.createElement("TBODY");
tblTitle.appendChild(tbdTitle); trTitle = document.createElement("TR");
trTitle. = changeItemWindowDisplay;
tdTitle_sv = document.createElement("TD");
tdTitle_sv.innerHTML = textDefault;
tdTitle_sv.width = widthObject - 14 - 4 - 4;
tdTitle_sv.valign = "absmiddle";
tdTitle_sv.onselectstart = function(){return false;};
tdTitle_sv.style.font = font_tag;
if(!objSelectBox.disabled) tdTitle_sv.style.color = normal_color;
else tdTitle_sv.style.color = disabled_color;
tdTitle_sv.style.cursor = "default";
tdTitle_sv.style.background = normal_bgcolor;
tdTitle_sv.style.verticalAlign = "text-bottom";
trTitle.appendChild(tdTitle_sv);
tdTitle = document.createElement("TD");
tdTitle.width = "14";
tdTitle.align = "center";
tdTitle.onselectstart = function(){return false;};
imgArrow = document.createElement("IMG");
imgArrow.src = arrow_image;
imgArrow.valign = "bottom";
imgArrow.style.filter = "gray()";
tdTitle.appendChild(imgArrow);
trTitle.appendChild(tdTitle);
tbdTitle.appendChild(trTitle); insertAdjacentElement("afterEnd",tblTitle);
} // 옵션 항목 창을 설정
function initializeItemWindow(){
objItemWindow = createPopup();
objItemDocument = objItemWindow.document;
objItemBody = objItemDocument.body;
with(objItemBody.style){
border = normal_border_tag;
overflowY = "auto";
scrollbarFaceColor = "#FFFFFF";
scrollbarShadowColor = "#ffffff";
scrollbarHighlightColor = "#ffffff";
scrollbar3dlightColor = "#ffffff";
scrollbarDarkShadowColor = "#ffffff";
scrollbarTrackColor = "#F0F0F0";
scrollbarArrowColor = "#c8c8c8";
buttonTextColor = "#ffffff";
}
} // 옵션 항목 테이블 설정
function initializeItemTable(){
// 아이템 출력 테이블 생성 및 셋팅
tblItem = objItemDocument.createElement("TABLE");
tblItem.cellSpacing = 2;
tblItem.cellPadding = 2;
tblItem.style.width = widthItemTable;
tblItem.style.color = normal_color;
tblItem.style.background = normal_bgcolor; tbdItem = objItemDocument.createElement("TBODY");
tblItem.appendChild(tbdItem); trItem = new Array();
tdItem = new Array();
for(i=0; i<objSelectBox.length; i++){
textSelectBox = objSelectBox.options[i].text;
valueSelectBox = objSelectBox.options[i].value;
var tooltip = objSelectBox.options[i].tooltip; trItem[i] = objItemDocument.createElement("TR");
tdItem[i] = objItemDocument.createElement("TD");
if(tooltip != null) tdItem[i].title = tooltip;
tdItem[i].innerHTML = " " + textSelectBox;
tdItem[i].setAttribute("key",i);
tdItem[i].height = "18";
tdItem[i].vAlign = "bottom";
tdItem[i]. = function(){eventMouseOverIT(this.getAttribute("key"))}
tdItem[i]. = function(){changeSelectBoxValue(this.getAttribute("key"))}
tdItem[i].onselectstart = function(){return false;};
tdItem[i].style.font = font_tag;
tdItem[i].style.color = normal_color;
tdItem[i].style.background = normal_bgcolor;
tdItem[i].style.cursor = "default";
tdItem[i].style.verticalAlign = "bottom";
trItem[i].appendChild(tdItem[i]);
tbdItem.appendChild(trItem[i]);
} objItemBody.insertAdjacentElement("beforeEnd",tblItem);
} //-------- 기타 함수
// 옵션 항목에 적용된 스타일 초기화
function removeItemStyle(){
for(i=0; i<countItem; i++){
tdItem[i].style.color = normal_color;
tdItem[i].style.background = normal_bgcolor;
}
} // 셀렉트박스의 값을 변경
function changeSelectBoxValue(idx){
objSelectBox.selectedIndex = idx;
tdTitle_sv.innerHTML = objSelectBox.options[idx].text;
closeItemWindow()
} // 문자열의 길이를 계산
function getStringLength(string){
var i, j=0; for(i=0;i<string.length;i++) {
lengthString = escape(string.charAt(i)).length;
if(lengthString > 4) j++;
j++;
} return j;
} // 문자열의 넓이를 픽셀 단위로 계산
function getStringPixelWidth(string_value){
var ascii_code;
var string_value_length = string_value.length;
var character;
var character_width;
var character_length;
var total_width = 0;
var total_length = 0; var special_char_size = 6;
var multibyte_char_size = 12;
var base_char_start = 32;
var base_char_end = 127;
var ascii_char_size = Array(4,4,4,6,6,10,8,4,5,5,6,6,4,6,4,6,6,6,6,6,6,6,6,6,6,6,4,4,8,6,8,6,12,8,8,9,8,8,7,9,8,3,6,8,7,11,9,9,8,9,8,8,8,8,8,10,8,8,8,6,11,6,6,6,4,7,7,7,7,7,3,7,7,3,3,6,3,11,7,7,7,7,4,7,3,7,6,10,7,7,7,6,6,6,9,6); for(i=0; i<string_value_length; i++){
character = string_value.substring(i,(i+1));
ascii_code = character.charCodeAt(0); if(ascii_code < base_char_start){
character_width = special_char_size;
}else if(ascii_code <= base_char_end){
idx = ascii_code - base_char_start;
character_width = ascii_char_size[idx];
}else if(ascii_code > base_char_end){
character_width = multibyte_char_size;
}
total_width += character_width;
} return total_width;
}
</script>
</public:component>
---------------------------------------------------------- 위 내용을 select.htc에 삽입 2. css 에 다음과 같이 추가. 방법1 ) select{behavior: url('/inc/common/select.htc');} ///모든 셀렉트 박스에는 위의 이쁜 셀렉트박스를 다 적용한다. 방법2) .select{behavior: url('/inc/common/select.htc');} 셀렉트 박스를 루프시켜 함수로 짠다음 자스코드로 정리해놓은 내 코드에서는 오류가 좀있음 따라서 나의 경우에는 시트에서 하나의 이름을 주어주었다. !) htc 파일의 경로는 각자 입맛에 맞게. 3. 셀렉트박스를 쓸곳에 (html/php)문서등 삽입 2번의 방법1일 경우) <select setImage="/make_img/select.gif" name=key onchange="location='/?mode=manager/info.php&key='+<?=($posmer[charset]=='UTF-8'?'encodeURI(this.value)':'this.value');?>;"> <option value=''>선택하여주세요</option> <?=get_pos_list($member[mb_3])?> </select> ## 위와 같이 코드부분에 강조색 부분(setimage) 만 꼭 삽입해준다. 2번의 방법2일 경우) <select class="select" setImage="/make_img/select.gif" name=key onchange="location='/?mode=manager/info.php&key='+<?=($posmer[charset]=='UTF-8'?'encodeURI(this.value)':'this.value');?>;"> <option value=''>선택하여주세요</option> <?=get_pos_list($member[mb_3])?> </select> ## 위와 같이 코드부분에 강조색 부분(setimage/class) 만 꼭 삽입해준다. !) 주의할점은 select.gif와 같은 이미지파일이 존재 하여야한다. 이는 셀렉트 박스의 오른구석의 화살표 이미지 이다. ------------------------------------------------------------ 이와 같이 아주 간단히 만들어 보았고, 응용은 알아서들 자스소스 저작권(htc)은 원제작자에게 있고, 문제가 될시에는 즉각 삭제토록 하겠습니다.
by Anna 안나 2008. 2. 24. 22:13