如何在javascript中自动扩展html select元素

时间:2010-05-27 18:02:55

标签: javascript html select expand

我的菜单中有一个(隐藏的)html选择对象附加到菜单按钮链接,因此单击该链接会显示该列表,以便您可以从中进行选择。

当您点击该按钮时,它会调用一些javascript来显示<select>。单击<select>会隐藏列表。我真正想要的是让<select>看起来完全展开,就像你点击了“向下”箭头一样,但是我无法让它工作。我已经尝试了很多不同的方法,但无法取得任何进展。我现在正在做的是:

<li>
    <a href="javascript:showlist();"><img src="/images/icons/add.png"/>Add favourite</a>
    <select id="list" style="display:none; onblur="javascript:cancellist()">
    </select>
</li>

// in code
function showlist() {
    //using prototype not jQuery
    $('list').show();  // shows the select list
    $('list').focus(); // sets focus so that when you click away it calles onblur()
}
  • 我尝试过调用$('list').click()
  • 我尝试过设置onfocus="this.click()" 但在这两种情况下我都会
  

未捕获TypeError:对象#没有方法'click'

这个特殊的link text表示它支持标准函数。

我已经尝试设置有效的.size = .length,但外观不同(当你点击打开元素时,它会漂浮在页面的其余部分。)

有人有任何建议吗?

5 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,想在我的应用程序中实现键盘导航,但选择的元素没有扩展,因此使用键盘的人将失去功能。我创建了ExpandSelect()函数,它模拟鼠标点击选择元素,它通过设置<select>属性创建另一个可以同时显示多个选项的size来实现,代码托管在Google代码上网站,ExpandSelect.js只有4 KB,请看截图并在此处下载:

http://code.google.com/p/expandselect/

截图

在模拟点击时,GUI有一点点差异,但这并不重要,请亲自看看:

点击鼠标时

MouseClicking http://expandselect.googlecode.com/hg/mouseclick_manyoptions.jpg

模仿点击时:

EmulatingClicking http://expandselect.googlecode.com/hg/emulateclick_manyoptions.jpg

项目网站上的更多截图,链接如上。

答案 1 :(得分:0)

这里有一个简单的解决方案,AUTO-EXPANDED选择菜单(所有选项都可见)

<select name="ddlTestSelect" id="ddlTestSelect" style="width:200px;position:absolute;">
  <option selected="selected" value="0">defaulttt</option>
  <option>option 2</option>
  <option>option 3</option>
  <option>option 4</option>
</select>
<script type="text/javascript">
 var slctt=document.getElementById("ddlTestSelect");
 slctt.size=slctt.options.length;if(slctt.options.length>1)slctt.style.width='470px';
</script>

答案 2 :(得分:-1)

您遇到语法错误。它应该是:

$('#list').click();

您忘记了#

答案 3 :(得分:-1)

请试试这个:

function showlist() {
    //using prototype not jQuery
    $('#list').show();  // shows the select list
    $('#list').focus(); // sets focus so that when you click away it calles onblur()
}

答案 4 :(得分:-2)

最简单的方法是使用&#34;倍数&#34; HTML中的属性

<select multiple></select>

您还可以添加样式属性来设置列表的高度

<select multiple style="height:150px;"></select>