Word wrap options in a select list

2019-01-03 06:56发布

Is it possible to wrap long options within a select list?

I have a dynamic select list, and some of the options are pretty lengthy. I'd like options that are too long to wrap to the next line. Beyond that, I'd like to indent those lines.

My solution if this isn't possible is to just trim the result to n characters.

Here's what I have:

I'm a short option
This is a really really really long option
This one isn't too bad
But whoa look how long I am! I go on forever!

And here's what I'd like to have:

I'm a short option
This is a really really 
    really long option
This one isn't too bad
But whoa look how long 
    I am! I go on forever!

2条回答
放荡不羁爱自由
2楼-- · 2019-01-03 07:45

you cant do this with a standard <option> you will need to roll-your-own or find a menu plugin

查看更多
趁早两清
3楼-- · 2019-01-03 07:52

Here is a quick and pure jQuery solution that may help some. Outside of creating your own drop down and pulling the values/text from a hidden select as mentioned by Scott Evernden. This will give you some room to play with. It doesn't cut off in the middle of a word but at the same time it doesn't wrap the text. It will put the full text into the title so a user may rollover and see the full text word wrapped. It will then use the maxChar setting to go to a certain number of characters then look for the end of the word it is on so as not to cut off the word. The min-width of the option should keep it inline with the select but go ahead and play with the maxChar variable and it should keep it from going outside the bounds. This is a short workaround as I would in most cases go with a customized solution but for quick lists where users can know what they are picking with the first word or two this works great. Hope this helps someone:

var optionText, array = [], newString, maxChar = 40;
$('select').each(function(){
    $(this).find('option').each(function(i,e) {
        $(e).attr('title',$(e).text());
        optionText = $(e).text();
        newString = '';
        if (optionText.length > maxChar) {
            array = optionText.split(' ');
            $.each(array,function(ind,ele) { 
                newString += ele+' ';
                if (ind > 0 && newString.length > maxChar) {
                    $(e).text(newString);
                    return false;
                }
            });

        }
    });
});
查看更多
登录 后发表回答