CSS 在选择框的选项中设置宽度

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

Set Width at Option of Select Box

csshtml-select

提问by Mahedi Sabuj

enter image description here

在此处输入图片说明

In the picture, the width of option is larger than the select box. I want to set width of those options as same as select box & for those larger options set text-overflow as ellipsis. Any help would be appreciated.

图中选项的宽度大于选择框的宽度。我想将这些选项的宽度设置为与选择框相同,对于那些较大的选项,将文本溢出设置为省略号。任何帮助,将不胜感激。

Here is what I tried:

这是我尝试过的:

Html

html

<select>
    <option>Select your University</option>
    <option>Bangladesh University of Engineering and Technology</option>
    <option>Mawlana Bhashani Science and Technology University</option>
</select>

Css

css

select, option {
    width: 250px;
}

option {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

Fiddle: https://jsfiddle.net/3bsbcqfz/

小提琴https: //jsfiddle.net/3bsbcqfz/

回答by dinindu

I tried to find a solution from CSS. But I failed to do it. Doesn't matter, I have written a simple javascript code for it. This is can do it something for it.

我试图从 CSS 中找到解决方案。但我没能做到。没关系,我已经为它编写了一个简单的 javascript 代码。这是可以为它做点什么的。

function shortString(selector) {
  const elements = document.querySelectorAll(selector);
  const tail = '...';
  if (elements && elements.length) {
    for (const element of elements) {
      let text = element.innerText;
      if (element.hasAttribute('data-limit')) {
        if (text.length > element.dataset.limit) {
          element.innerText = `${text.substring(0, element.dataset.limit - tail.length).trim()}${tail}`;
        }
      } else {
        throw Error('Cannot find attribute \'data-limit\'');
      }
    }
  }
}

window.onload = function() {
  shortString('.short');
};
select {
  width: 250px;
}

option {
  width: 250px;
}
<select name="select" id="select">
  <option class='short' data-limit='37' value="Select your University">Select your University</option>
  <option class='short' data-limit='37' value="Bangladesh University of Engineering and Technology">Bangladesh University of Engineering and Technology</option>
  <option class='short' data-limit='37' value="Mawlana Bhashani Science and Technology University">Mawlana Bhashani Science and Technology University</option>
</select>

回答by Mahedi Sabuj

At last, I come up with the solution by creating Custom Drop-downusing ul, li.Here is the solution:

最后,我通过使用以下解决方案创建自定义下拉列表ul, li.提出解决方案:

FIDDLE DEMO

小提琴演示

HTML

HTML

<div class='custom-select'>
    <div class="selected">
       <span class='text'>Select</span>
    </div>
    <div class='select-box'>
       <ul class='select-list'>
          <li data-row='0' data-value=''>
              Select
          </li>
          <li data-row='1' data-value='BUET'>
              Bangladesh University of Engineering and Technology
          </li>
          <li data-row='2' data-value='MBSTU'>
              Mawlana Bhashani Science and Technology University
          </li>
       </ul>
    </div>
</div> 

CSS

CSS

div.custom-select 
{
    height: 40px;
    width: 400px;
    position: relative;
    background-color: #F2F2F2;
    border: 1px solid #E4E4E4;
}

div.selected
{
    width: inherit;
    cursor: pointer;
    line-height: 20px;
    display: inline-block;
}

div.selected > .text
{
    padding: 10px;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

div.select-box
{
    display: none;
    width: 100%;
    z-index: 10029;
    position: absolute;
    border-radius: 3px;
    box-shadow: 0 8px 20px #000000;
    box-shadow: 0 8px 20px rgba(0,0,0,.35)
}

div.select-box.active
{
    display: block;
}

div.select-box.drop-up
{
    top: auto;
    bottom: 100%;
}

ul.select-list
{
    margin: 0;
    padding: 10px;
    list-style-type: none;
}

ul.select-list li
{
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

ul.select-list li:hover,
ul.select-list li.active
{
    background-color: #999999;
}

JavaScript

JavaScript

$(document).ready(function (){
    $("div.selected").on("click", function () {
        var hasActiveClass = $("div.select-box").hasClass("active");

        if (hasActiveClass === false) {
            var windowHeight = $(window).outerHeight();
            var dropdownPosition = $(this).offset().top;
            var dropdownHeight = 95; // dropdown height

            if (dropdownPosition + dropdownHeight + 50 > windowHeight) {
                $("div.select-box").addClass("drop-up");
            }
            else {
               $("div.select-box").removeClass("drop-up");
            }

            var currentUniversity = $(this).find('text').text().trim();

            $.each($("ul.select-list li"), function () {
                var university = $(this).text().trim();
                if (university === currentUniversity)
                    $(this).addClass("active");
                else
                    $(this).removeClass("active");
            });
        }

        $("div.select-box").toggleClass("active");
    });

    $("ul.select-list li").on("click", function () {
        var university = $(this).html();
        $("span.text").html(university);
        $("div.select-box").removeClass("active");
    });

    $("ul.select-list li").hover(function () {
        $("ul.select-list li").removeClass("active");
    });

    $(document).click(function (event) {
        if ($(event.target).closest("div.custom-select").length < 1) {
            $("div.select-box").removeClass("active");
        }
    });

});

回答by Islam Elshobokshy

Another simple jquery solution is to rewrite the option's length manually to get the wanted size as follow :

另一个简单的 jquery 解决方案是手动重写选项的长度以获得所需的大小,如下所示:

$('option').each(function() {
  var optionText = this.text;
  var newOption = optionText.substring(0, 36);
  $(this).text(newOption + '...');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<select style="width:250px">
    <option>Select your University</option>
    <option>Bangladesh University of Engineering and Technology</option>
    <option>Mawlana Bhashani Science and Technology University</option>
</select>

回答by ellipsis

You can use javascript to make the length of the option text to be less so as that it matches the length of the option. I found no solution for only using css

您可以使用 javascript 使选项文本的长度更短,以便与选项的长度相匹配。我没有找到仅使用 css 的解决方案

var e=document.querySelectorAll('option')
e.forEach(x=>{
if(x.textContent.length>20)
x.textContent=x.textContent.substring(0,20)+'...';
})
select
{
width:160px;
}
<select>
<option>fwefwefwefwe</option>
<option>fwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwe</option>
</select>