Dynamically truncate

2019-04-17 01:13发布

By default, the selector list shown for a <select></select> element will be as wide as the widest <option></option> child it contains. If I hardcode the width of the select tag with CSS to make it more narrow, the widest option is truncated in the display.

I want to trim down the option text to fit the selection list, appending ... (ellipsis) to show that it's truncated when the option is selected, however, when I expand the dropdown I want the text in the dropdown to be full width, without trailing ellipsis.

How would I accomplish that?

3条回答
小情绪 Triste *
2楼-- · 2019-04-17 01:29

I believe what you're looking for is:

option {
  width: 200px; // Adjustable
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

That will automatically force the select options to be the specified width, and convert any 'overflowing' text to ellipsis that remains within the bounds :)

Hope this helps!

查看更多
放我归山
3楼-- · 2019-04-17 01:50

Using css and jQuery :

select, option.selected {
    width:100px;
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
}

jQuery

$('select').on('change',function(){
    $(this).find('option').removeClass('selected');
    $(this).find('option:selected').addClass('selected');
});

demo

查看更多
4楼-- · 2019-04-17 01:52

I found the solution for chrome here:

https://stackoverflow.com/a/26627224/4743939

Using this approach, the caret icon in select tag will disappear, so you might want to use a background image for it.

查看更多
登录 后发表回答