如果给下拉列表设置了宽度,有的项内容很长,那么就显示不全,解决这个问题的一个比较好的办法,是给每一项设置title提示,这样当鼠标放在列表上时就可以提示完整信息。
JS方法定义如下:
function SetOptionTitle()


{
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;
}
}
}
}
}
这个方法只支持IE7+以上版本,IE6不支持,解决IE6也支持的办法如下:
当鼠标悬停到<select>时,创建一个这个下拉列表的副本,同时把焦点移到这个副本上,把副本的样式设成绝对定位,而且盖在原来的下拉列表上,宽度根据option的显示内容自动拉伸,当这个副本失去焦点,或者用户对它进行了选择操作后,获取副本的selectedIndex,赋给原来的select对象。具体代码如下:
<!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 ZDBASE.COM">ZDBASE.COM</option>
<option id="B" title="this is png图标">png图标</option>
<option id="C" title="this is 网页素材">网页素材</option>
</select>
</div>
</form>
</body>
</html>