读书人

固定宽度的select上拉列表option选项显

发布时间: 2012-09-08 10:48:07 作者: rapoo

固定宽度的select下拉列表option选项显示不全的解决办法
昨天因为工作需要,研究了下select下拉列表,发现一段JS并进行了修改,因为源代码存在一个bug,所以我进行了稍微修改并注明,希望能对大家有所帮助!

固定宽度的select下拉列表option选项显示不全的解决办法:
在实际的开发中在页面中为了布局的需要,下拉菜单<select>的宽度要设成比较小的值,但这时由于包含的选择项<option>的内容比较长,那么超出select宽度的部分将会被截断,如果option显示的内容又比较重要,必须完整地展现出来,这就成为一个必须要解决的问题。
在IE7和Firefox中,由于支持了<option>的title属性,我们可以想办法给option标记设置title属性(内容可以与显示的值相同或者不同)。如果是已经做好的页面,不想再做太多改动,可以用下面的脚本,自动遍历页面上的所有<select>,给所有的option加上与text相同的title。

看下面的代码:

<script type="text/javascript">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;}}}}}</script>


但是,IE6并不支持<option>的title属性,这个方法在IE6下完全不起作用!但是由于IE6还是市场的主流,我们还是想办法解决这个问题.
目前想到的办法是:当鼠标悬停到<select>时,创建一个这个下拉列表的副本,同时把焦点移到这个副本上,把副本的样式设成绝对定位,而且盖在原来的下拉列表上,宽度根据option的显示内容自动拉伸,当这个副本失去焦点,或者用户对它进行了选择操作后,获取副本的selectedIndex,赋给原来的select对象。具体代码如下:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>http://blog.sina.com.cn/delectiveconan</title><script type="text/javascript">function FixWidth(selectObj){var newSelectObj = document.createElement_x_x("select");newSelectObj = selectObj.cloneNode(true);newSelectObj.setAttribute("ID", "aa");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 = "";}var rollback = function(){ RollbackWidth(selectObj, newSelectObj); };newSelectObj.onmouseout= rollback;//新增加的事件,解决一处BUGnewSelectObj.focus();newSelectObj.onfocus = function(){ newSelectObj.onmouseout=null; };//新增加的事件,解决BUGnewSelectObj.onblur = rollback;newSelectObj.onchange = rollback;selectObj.style.visibility = "hidden";document.body.appendChild(newSelectObj);}function RollbackWidth(selectObj, newSelectObj){selectObj.selectedIndex = newSelectObj.selectedIndex;selectObj.style.visibility = "visible";document.body.removeChild(newSelectObj);}</script> <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"></option><option id="B" title="this is B">http://www.phpzixue.cn/</option><option id="C" title="this is C">phpzixue.cn</option></select></div></form></body></html>


有了这个demo,我们就可以把其中的js提取出来,应用到项目中需要的地方了。
目前这种方式是给select注册了onmouseover,对于鼠标操作是没什么问题,如果用户是按tab键移动焦点就无效了。有兴趣的同学可以考虑解决一下.

读书人网 >Web前端

热点推荐