預設的 select box 的寬度會依照 option 裡的值(value) 長短而自動 resize 寬度, 在很多 select box 的畫面裡會不太好太, 解法有2:
- 1. css (建議), min-width & max-width 屬性.
- 2. javascript.
解法1:
Example
Set the minimum width of a paragraph:
p{
min-width:1000px;
}
Browser Support: ALL Browser
The min-width property is supported in all major browsers.
Note: IE6 and earlier versions do not support the min-width property.
html code:
<select name="Select1" style="min-width:100px; max-width:120px;">
執行畫面 (screent shot):
解法2: javascritp
執行畫面:
javascript source code:
==============
<!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></title>
<script type="text/javascript">
function FixWidth(selectObj)
{
var newSelectObj = document.createElement("select");
newSelectObj = selectObj.cloneNode(true);
newSelectObj.selectedIndex = selectObj.selectedIndex;
newSelectObj.onmouseover = null;
var e = selectObj;
var absTop = e.offsetTop;
var absLeft = e.offsetLeft;
while(e = e.offsetParent)
{
absTop += e.offsetTop;
absLeft += e.offsetLeft;
}
with (newSelectObj.style)
{
position = "absolute";
top = absTop + "px";
left = absLeft + "px";
width = "auto";
}
var rollback = function(){ RollbackWidth(selectObj, newSelectObj); };
if(window.addEventListener)
{
newSelectObj.addEventListener("blur", rollback, false);
newSelectObj.addEventListener("change", rollback, false);
}
else
{
newSelectObj.attachEvent("onblur", rollback);
newSelectObj.attachEvent("onchange", rollback);
}
selectObj.style.visibility = "hidden";
document.body.appendChild(newSelectObj);
newSelectObj.focus();
}
function RollbackWidth(selectObj, newSelectObj)
{
selectObj.selectedIndex = newSelectObj.selectedIndex;
selectObj.style.visibility = "visible";
document.body.removeChild(newSelectObj);
}
</script>
</head>
<body>
<form method="post">
<div style="width:100px; height:100px; margin:100px; padding:10px; background:gray;">
<select name="Select1" style="width:80px;" onmouseover="FixWidth(this)">
<option id="A" title="this is A">AAAAAAAAAAAAAAA</option>
<option id="B" title="this is B">BBBBBBBBBBBBBBB</option>
<option id="C" title="this is C">CCCCCCCCCCCCCCC</option>
</select>
</div>
</form>
</body>
</html>