固定宽度的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><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>