CSS 使选择元素中的文本太长时换行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23018619/
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-30 02:15:47  来源:igfitidea点击:

Make text in select element wrap when too long?

css

提问by Evanss

I have a select list where the text within the options is too long as is getting cropped. Is it possible to make the text wrap instead so that all of it is visible?

我有一个选择列表,其中选项中的文本太长而被裁剪。是否可以让文本换行以使其全部可见?

enter image description here

在此处输入图片说明

http://jsfiddle.net/W4KG7/

http://jsfiddle.net/W4KG7/

<select>
    <option>This is option 1</option>
    <option>This is option 2</option>
</select>

select {
    width: 92px;
}

采纳答案by Shlomi Hassid

Using CSS to do this will only work in Chrome...

使用 CSS 来做到这一点只能在 Chrome 中工作......

You can't do it just by using CSS, but you can use some jQuery for a "look like" solution.

你不能仅仅通过使用 CSS 来做到这一点,但你可以使用一些 jQuery 来实现“看起来像”的解决方案。

Take a look at the this quick demo I made: JSnippet DEMO

看看我制作的这个快速演示:JSnippet DEMO

As you can see it behaves like you wanted - I'm wrapping the select box with a DIVand adding another one that will overlap the select box - he takes the select box fixed width minus the button of the select box. Now I'm assigning to this div the same appearance as the select box + The selected value.

正如您所看到的,它的行为与您想要的一样 - 我用 a 包裹选择框DIV并添加另一个与选择框重叠的框 - 他将选择框固定宽度减去选择框的按钮。现在我为这个 div 分配与选择框 + 选定值相同的外观。

Every time the select box will be changed the new value will be set in the mask we created and the calculated new height will be set to the select box to.

每次更改选择框时,都会在我们创建的掩码中设置新值,并将计算出的新高度设置为选择框。

Here is the jQuery code:

这是jQuery代码:

$(function(){
var mYbrowser = detectBrows();
console.log(mYbrowser[0]);
$('select').each(function(index,ele){

    //get current style and fixed width:
    var renderWidth = $(ele).outerWidth();
    var renderWidthFixed = renderWidth;
    var borderstyle = $(ele).css("border-bottom-style");
    var bordercolor = $(ele).css("border-bottom-color");
    var borderwidth = $(ele).css("border-bottom-width");
    var font = $(ele).css("font");
    var defaultValue = $(ele).val();
    if (borderwidth == "0px") { borderwidth = "1px"; /*FF*/ }
    $(ele).css({ cursor:"pointer" });

    // set by browser (different buttons):
    var borderRightParsed = borderwidth +" " + borderstyle + " " + bordercolor;
    var topParsed = Math.round(parseInt(borderwidth.replace(/[^0-9\.]+/g,"")));
    switch(mYbrowser[0]) {
            case "MSIE": renderWidthFixed = renderWidth-28; break;
            case "I": renderWidthFixed = renderWidth-28; break;                 
            case "Chrome": renderWidthFixed = renderWidth-30; break;
            case "Firefox": 
                            renderWidthFixed = renderWidth-27; 
                            borderRightParsed= "0"; 
                            if (index > 0) topParsed++;
                            break; 
    }
    //wrap + add a overlapping layer that will hide content and calculate the correct height:
    $(ele).wrap($('<div />').css({width:renderWidth, margin:0, padding:0, position:"relative"}));
    $(ele).after($("<div>" + defaultValue + "</div>")
                   .css({
                       minHeight:20,
                       padding:"5px 0px 5px 8px",
                       width:renderWidthFixed,
                       backgroundColor:"white",
                       whiteSpace:"pre-wrap",
                       position:"absolute",
                       borderRight:borderRightParsed,
                       top:topParsed,
                       cursor:"default",
                       left:borderwidth,
                       font:font
                   })
                );
    //set select box new height:
    setHeight(ele);

    //append change behavior:
    $(ele).change(function(){
        $(ele).next('div').text($(ele).val());
        setHeight(ele);
    });

});

function setHeight(ele) {
    var newHeight = $(ele).next('div').outerHeight();
    $(ele).height(newHeight);

}

function detectBrows(){
    var ua= navigator.userAgent, tem, 
        M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE '+(tem[1] || '');
        }
        if(M[1]=== 'Chrome'){
            tem= ua.match(/\bOPR\/(\d+)/)
            if(tem!= null) return 'Opera '+tem[1];
        }
        M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
        return M;        
}
});

Its simple and not complicated - the problem is that the select box element behave and look different on each browser. I added a small quick function to detect which browser is used and fine tuning his unique values.

它简单而不复杂 - 问题在于选择框元素在每个浏览器上的行为和外观都不同。我添加了一个小的快速功能来检测使用的是哪个浏览器并微调他的唯一值。

This method can be Improved but that's a good starting point.

这种方法可以改进,但这是一个很好的起点。

Shlomo

什洛莫

回答by mr_greb

select {
    width: 92px;
    white-space:pre-wrap;
}

This only appears to work in Google Chrome. https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

这似乎只适用于谷歌浏览器。 https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

回答by Vic Seedoubleyew

It seems there is no way to accomplish this in Firefox without reinventing the wheel.

如果不重新发明轮子,似乎没有办法在 Firefox 中实现这一点。

The solution I have come up with achieves this for other browsers, and uses an ellipsis in Firefox:

我提出的解决方案为其他浏览器实现了这一点,并在 Firefox 中使用了省略号:

select {
    max-width: 100%;
    white-space: normal;
    /* For Firefox: */
    text-overflow: ellipsis;
}