定义select / option元素

时间:2016-02-19 09:58:11

标签: html css html-select maxlength

我想创建一个<select>字段。默认情况下,此字段的长度由最长<option>定义。当我需要整个选择字段100%的父div时,是否可以定义可见选择选项的最大长度?

让我在代码中告诉你:

<div class = "my-container">
  <select name="myselect" id="myselect">
    <option>abc</option>
    <option>xyz1</option>
    <option>really really long long long long long string</option>
  </select>
</div>

样式:

.my-container{
  width:200px;
}
#myselect{
  width: 100%;
}

现在我希望我的选择字段宽度为100%但是!我想在这个选项中显示只有20个单词(或某个px值)的选项值,然后“......”示例:

Verylong
Verylonglonglong... (original value: Verylonglonglong1234567789)

我尝试将溢出属性添加到#myselect,但它对我不起作用。

1 个答案:

答案 0 :(得分:2)

解决问题的JQuery解决方案:

var maxLength = 15;
$('#myselect > option').text(function(i, text) {
    if (text.length > maxLength) {
        return text.substr(0, maxLength) + '...';  
    }
});
.my-container{
  width:200px;
}
#myselect{
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class = "my-container">
  <select name="myselect" id="myselect">
    <option>abc</option>
    <option>xyz1</option>
    <option>really really long long long long long string</option>
  </select>
</div>

相关问题