jQuery HTML Select 标签显示带有 10 个选项的垂直滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24119643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:27:48  来源:igfitidea点击:

HTML Select tag show vertical scroll with 10 option

jqueryhtmlcssselectvertical-scroll

提问by RohitK

I want to make a select box like this

我想做一个这样的选择框

enter image description here

在此处输入图片说明

with 10 select option, when I try to add more than 15 option it show vertical scroll bar, but not show when it have 10 option.

有 10 个选择选项,当我尝试添加超过 15 个选项时,它会显示垂直滚动条,但在有 10 个选项时不显示。

is there any way to achieve this.

有什么办法可以做到这一点。

采纳答案by Jai

apply a size="10"to your select.

将 asize="10"应用于您的选择。

something like:

就像是:

<select size="10">
   // all your options
</select>


You have to put some style to the label like border, background-image etc.

您必须为标签添加一些样式,例如边框、背景图像等。

Something like this to be done:

像这样的事情要做:

<label id='choose' for='options'>Select options</label>
<br clear='all' />
<select id='options' size="10" style='display:none;'>
    // all the options
</select>

then use this jQuery code:

然后使用这个 jQuery 代码:

$('#choose').click(function(){
    $(this).siblings('select').toggle();
});

Demo @ Fiddle

演示@小提琴



Try with this:

试试这个:

$('#choose').click(function (e) {
    e.stopPropagation();
    $(this).siblings('select').css('width', $(this).outerWidth(true)).toggle();
});

$('#options').change(function (e) {
    e.stopPropagation();
    var val = this.value || 'Select options';
    $(this).siblings('#choose').text(val);
    $(this).hide();
});


As you commented:

正如你评论的那样:

when size is greater then 1 of select tag, its not showing blue background in hover, when i add background through css option:hover, its working in FF, but not in chrome and safari.

当尺寸大于选择标签的 1 时,它在悬停时不显示蓝色背景,当我通过 css option:hover 添加背景时,它在 FF 中工作,但在 chrome 和 safari 中不工作。

so you can mockup with this:

所以你可以用这个模型:

$('#options').find('option').on({
    mouseover: function () {
        $('.hover').removeClass('hover');
        $(this).addClass('hover');
    },
    mouseleave: function () {
        $(this).removeClass('hover');
    }
});

Demo with hover class.

带有悬停类的演示

回答by zafus_coder

Size attribute specifies the number of visible options in a drop-down list. If the value of the size attribute is greater than 1, but lower than the total number of options in the list, the browser will add a scroll bar to indicate that there are more options to view.

大小属性指定下拉列表中可见选项的数量。如果 size 属性的值大于 1,但小于列表中的选项总数,则浏览器会添加滚动条以指示有更多选项可供查看。

So use <select size="10">..</select>

所以用 <select size="10">..</select>