2009-09-20 5 views
0

자바 스크립트를 사용하여 드롭 다운 목록에 새 옵션을 동적으로 추가하고 목록을 확장하려면 목록의 오른쪽에있는 화살표가있는 선택된 항목으로 되돌릴 때 선택한 텍스트는 옵션 목록의 가장 넓은 텍스트만큼 넓습니다.선택 상자를 Hug Chosen 텍스트로 크기 조정 텍스트

그래서 상자의 텍스트 오른쪽에 여분의 공백이 없으면 무엇을 의미하는지 알면 상자의 너비를 텍스트의 크기로 줄이면됩니다.

덕분에 많은 사람이 :-)

+0

: 사용자가 자신의 선택을 할 때 <선택 ID = "DropDownList로"및 onblur = "fnOnBlur는()"> 그래서 그것은 시간이다 선택 사항을 표시합니다. 이제 선택한 텍스트와 일치하도록 선택 상자의 너비를 조정해야합니다. 우리가 할 수 있도록 DOM을 포함 할 것 같아요 : var sel = document.getElementById ("DropDownList"); 거기에서 일하십시오. 하지만 이런 종류의 DOM 조작에 익숙하지 않습니다. – Andy

답변

3

그것은 쉽게 나를 도울 수 있다면, 단지 숨겨진 옵션 (옵션의 제목에 복사)의 콘텐츠를 삭제 선택 초점을 복원 할 수 있습니다.

코드 : 나는 및 onblur 이벤트로 시작

<html><head><title>Auto size select</title> 

<script> 
var resized = false; 

function resizeSelect(selected) { 
    if (resized) return; 
    var sel = document.getElementById('select'); 
    for (var i=0; i<sel.options.length; i++) { 
    sel.options[i].title=sel.options[i].innerHTML; 
    if (i!=sel.options.selectedIndex) sel.options[i].innerHTML=''; 
    } 
    resized = true; 
    sel.blur(); 
} 

function restoreSelect() { 
    if (!resized) return; 
    var sel = document.getElementById('select'); 
    for (var i=0; i<sel.options.length; i++) { 
    sel.options[i].innerHTML=sel.options[i].title; 
    } 
    resized = false; 
} 
</script> 

</head> 
<body onload="resizeSelect(this.selectedItem)"> 
<select id="select" 
    onchange="resizeSelect(this.selectedItem)" 
    onblur="resizeSelect(this.selectedItem)" 
    onfocus="restoreSelect()"> 
<option>text text</option> 
<option>text text text text text</option> 
<option>text text text </option> 
<option>text text text text </option> 
<option>text</option> 
<option>text text text text text text text text text</option> 
<option>text text</option> 
</select> 
</body></html> 
+0

감사합니다 Pedro! 멋진 솔루션 :-) – Andy

+0

+1 감사합니다 Pedro -이 모든 브라우저에서 작동합니다 :) –

관련 문제