不少時候在頁面中爲了佈局的需要,下拉列表<select>的寬度需要設成比較小的值,這時如果恰巧它包含的選擇項<option>的內容比較長,那麼超出select寬度的部分將會被截斷,如果option顯示的內容又比較重要,必須完整地展現出來,或者你是個完美主義者,那這就成了一個不大不小的問題了。
在IE7+、Firefox中,由於支持了<option>的title屬性,我們可以想辦法給option標記設置title屬性(內容可以與顯示的值相同或者不同)。如果是已經做好的頁面,不想再做太多改動,可以用下面的腳本,自動遍歷頁面上的所有<select>,給所有的option加上與text相同的title。
{
var selects = document.getElementsByTagName("select");
if (selects.length > 0)
{
for (var i = 0; i < selects.length; i++)
{
var options = selects[i].options;
if (selects[i].options.length > 0)
{
for (var j = 0; j < options.length; j++)
{
if (options[j].title == "")
options[j].title = options[j].text;
}
}
}
}
}
我目前想到的辦法是:當鼠標懸停到<select>時,創建一個這個下拉列表的副本,同時把焦點移到這個副本上,把副本的樣式設成絕對定位,而且蓋在原來的下拉列表上,寬度根據option的顯示內容自動拉伸,當這個副本失去焦點,或者用戶對它進行了選擇操作後,獲取副本的selectedIndex,賦給原來的select對象。具體代碼如下:
<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>
有了這個demo,我們就可以把其中的js提取出來,應用到項目中需要的地方了。
目前這種方式是給select註冊了onmouseover,對於鼠標操作是沒什麼問題,如果用戶是按tab鍵移動焦點就無效了。估計實際應用中這樣的情形不會很多,所以暫不考慮,有興趣的朋友可以再完善一下,或者看看有沒有更好的解決方法。
轉自:http://www.cnblogs.com/key/archive/2008/05/17/1201274.html