如何扩展“选择” 用户想要选择一个选项后的选项宽度?

发布于 2024-07-09 22:08:29 字数 447 浏览 16 评论 0原文

也许这是一个简单的问题,也许不是。 我有一个

<select style="width: 120px">
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
  <option>ABC</option>
</select>

我希望能够显示第二个选项,以便用户可以看到文本的完整长度。

就像其他一切一样。 这在 Firefox 中工作正常,但对我来说不适用于其他浏览器。

Maybe this is an easy question, maybe not. I have a <select> box where I hardcode the width to 120px:

<select style="width: 120px">
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
  <option>ABC</option>
</select>

I want to be able to show the second option so that the user can see the full length of the text.

Like everything else. This works fine in Firefox, but doesn't work with other browsers for me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

我是有多爱你 2024-07-16 22:08:29

我用以下代码解决了我的问题:

<div style="width: 180px; overflow: hidden;">
   <select style="width: auto;" name="abc" id="10">
     <option value="-1">AAAAAAAAAAA</option>
     <option value="123">123</option>
   </select>
</div>

希望能帮助到你!

I fixed my problem with the following code:

<div style="width: 180px; overflow: hidden;">
   <select style="width: auto;" name="abc" id="10">
     <option value="-1">AAAAAAAAAAA</option>
     <option value="123">123</option>
   </select>
</div>

Hope it helps!

如歌彻婉言 2024-07-16 22:08:29

如果您的选项预先存在于固定的

  • 您可以尝试为每个选项设置 title 属性。 这是非标准 HTML(如果您关心这里的这个小违规行为),但 IE(以及 Firefox)将在鼠标悬停时在鼠标弹出窗口中显示整个文本。
  • 当用户选择某些内容时,您可以使用 JavaScript 在某个定位的 DIV 中显示文本。 恕我直言,这是一种不太好的方法,因为它需要 JavaScript 才能工作,并且只有选择某些内容之后 - 之前才有效是值的变化,选择框不会触发任何事件。
  • 您根本不使用选择框,但实现其使用其他标记和 CSS 的功能。 不是我最喜欢的,但我想提一下。

如果您稍后通过 JavaScript 添加长选项,请查看此处:如何在 IE 中动态更新 HTML“选择”框

If you have the option pre-existing in a fixed-with <select>, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.

  • You could try and set the title attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.
  • You could use JavaScript to show the text in some positioned DIV when the user selects something. IMHO this is the not-so-nice way to do it, because it requires JavaScript on to work at all, and it works only after something has been selected - before there is a change in value no events fire for the select box.
  • You don't use a select box at all, but implement its functionality using other markup and CSS. Not my favorite but I wanted to mention it.

If you are adding a long option later through JavaScript, look here: How to update HTML “select” box dynamically in IE

甜味拾荒者 2024-07-16 22:08:29

很老的问题,但这是解决方案。 这里有一个使用 jquery 的工作片段。 它利用临时辅助select,将主选择中的选定选项复制到其中,以便可以评估主select 应具有的真实宽度。

$('select').change(function(){
  var text = $(this).find('option:selected').text()
  var $aux = $('<select/>').append($('<option/>').text(text))
  $(this).after($aux)
  $(this).width($aux.width())
  $aux.remove()
}).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option>ABC</option>
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
</select>

Very old question but here's the solution. Here you have a working snippet using jquery. It makes use of a temporary auxiliary select into which the selected option from the main select is copied, such that one can assess the true width which the main select should have.

$('select').change(function(){
  var text = $(this).find('option:selected').text()
  var $aux = $('<select/>').append($('<option/>').text(text))
  $(this).after($aux)
  $(this).width($aux.width())
  $aux.remove()
}).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option>ABC</option>
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
</select>

红颜悴 2024-07-16 22:08:29

将其放在 div 中
并给它一个 id,

<div id=myForm>

然后创建一个非常非常简单的 css 来配合它。

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

这就是你所需要的。

Place it in a div
and give it an id

<div id=myForm>

then create a really really simple css to go with it.

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

That's all you need.

傲世九天 2024-07-16 22:08:29

我通过在选择中将最小宽度和最大宽度设置为相同的值,然后将选择:焦点设置为自动来修复它。

select {
  min-width: 120px;
  max-width: 120px;
}
select:focus {
  width: auto;
}
<select style="width: 120px">
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
  <option>ABC</option>
</select>

I fixed it in my bootstrap page by setting the min-width and max-width to the same value in the select and then setting the select:focus to auto.

select {
  min-width: 120px;
  max-width: 120px;
}
select:focus {
  width: auto;
}
<select style="width: 120px">
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
  <option>ABC</option>
</select>

山川志 2024-07-16 22:08:29

这模仿了您寻找的大部分行为:

  <!--

     I found this works fairly well.

  -->

  <!-- On page load, be sure that something else has focus. -->
  <body onload="document.getElementById('name').focus();">
  <input id=name type=text>

  <!-- This div is for demonstration only.  The parent container may be anything -->
  <div style="height:50; width:100px; border:1px solid red;">

  <!-- Note: static width, absolute position but no top or left specified, Z-Index +1 -->
  <select
   style="width:96px; position:absolute; z-index:+1;"
   onactivate="this.style.width='auto';"
   onchange="this.blur();"
   onblur="this.style.width='96px';">
  <!-- "activate" happens before all else and "width='auto'" expands per content -->
  <!-- Both making a selection and moving to another control should return static width -->

  <option>abc</option>
  <option>abcdefghij</option>
  <option>abcdefghijklmnop</option>
  <option>abcdefghijklmnopqrstuvwxyz</option>

  </select>

  </div>

  </body>

  </html>

这将覆盖一些按键行为。

This mimics most of the behavior your looking for:

  <!--

     I found this works fairly well.

  -->

  <!-- On page load, be sure that something else has focus. -->
  <body onload="document.getElementById('name').focus();">
  <input id=name type=text>

  <!-- This div is for demonstration only.  The parent container may be anything -->
  <div style="height:50; width:100px; border:1px solid red;">

  <!-- Note: static width, absolute position but no top or left specified, Z-Index +1 -->
  <select
   style="width:96px; position:absolute; z-index:+1;"
   onactivate="this.style.width='auto';"
   onchange="this.blur();"
   onblur="this.style.width='96px';">
  <!-- "activate" happens before all else and "width='auto'" expands per content -->
  <!-- Both making a selection and moving to another control should return static width -->

  <option>abc</option>
  <option>abcdefghij</option>
  <option>abcdefghijklmnop</option>
  <option>abcdefghijklmnopqrstuvwxyz</option>

  </select>

  </div>

  </body>

  </html>

This will override some of the key-press behavior.

瞎闹 2024-07-16 22:08:29

尽管这个问题是 2008 年提出的,但在某些情况下您仍然希望选择框匹配当前选择的宽度而不是最长的选项。 所以这是一种现代方法:

它或多或少与 这个答案 中的原理相同,只是没有 jQuery。

  1. 获取选择元素并监听其变化。
  2. 创建一个新的 select 元素和选项,并将当前 selectedIndex 的文本传递给该选项。
  3. position:fixedvisibility:hidden 样式添加到新的 select 元素。 这确保了它不会影响您的布局,但仍然可以测量其边界框。
  4. 将选项附加到选择。
  5. 将选择附加到原始选择元素。
  6. 使用 getBoundingClientRect().width 获取新的所需尺寸。
  7. 根据新的尺寸设置原始宽度。
  8. 删除新的。
  9. 最初调度一个更改事件来触发此逻辑。
const select = document.querySelector('select')

select.addEventListener('change', (event) => {
  let tempSelect = document.createElement('select'),
      tempOption = document.createElement('option');

  tempOption.textContent = event.target.options[event.target.selectedIndex].text;
  tempSelect.style.cssText += `
      visibility: hidden;
      position: fixed;
      `;
  tempSelect.appendChild(tempOption);
  event.target.after(tempSelect);
  
  const tempSelectWidth = tempSelect.getBoundingClientRect().width;
  event.target.style.width = `${tempSelectWidth}px`;
  tempSelect.remove();
});

select.dispatchEvent(new Event('change'));
<select>
  <option>Short option</option>
  <option>Some longer option</option>
  <option>An very long option with a lot of text</option>
</select>

Even though this question is from 2008, there are still cases where you want the select box to match the width of the current selection rather than the longest option. So here's a modern approach to it:

It's more or less the same principle like in this answer just without jQuery.

  1. Get the select element and listen for changes on it.
  2. Create a new select element and option and pass the text of the current selectedIndex to the option.
  3. Add position: fixed and visibility: hidden styles to the new select element. This ensures, that it is not affecting your layout but its bounding box can still be measured.
  4. Append the option to the select.
  5. Append the select to the original select element.
  6. Get the needed dimensions of that new one using getBoundingClientRect().width
  7. Set the width of the original one based on the dimensions of the new one.
  8. Remove the new one.
  9. Dispatch a change event to trigger this logic initially.

const select = document.querySelector('select')

select.addEventListener('change', (event) => {
  let tempSelect = document.createElement('select'),
      tempOption = document.createElement('option');

  tempOption.textContent = event.target.options[event.target.selectedIndex].text;
  tempSelect.style.cssText += `
      visibility: hidden;
      position: fixed;
      `;
  tempSelect.appendChild(tempOption);
  event.target.after(tempSelect);
  
  const tempSelectWidth = tempSelect.getBoundingClientRect().width;
  event.target.style.width = `${tempSelectWidth}px`;
  tempSelect.remove();
});

select.dispatchEvent(new Event('change'));
<select>
  <option>Short option</option>
  <option>Some longer option</option>
  <option>An very long option with a lot of text</option>
</select>

内心激荡 2024-07-16 22:08:29

好吧,这个选项相当黑客,但应该可行。

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

这当然需要一个隐藏的 div。

<div id="hiddenDiv" style="visibility:hidden"></div>

哦,你需要 jQuery

Okay, this option is pretty hackish but should work.

$(document).ready( function() {
$('#select').change( function() {
    $('#hiddenDiv').html( $('#select').val() );
    $('#select').width( $('#hiddenDiv').width() );
 }
 }

Which would offcourse require a hidden div.

<div id="hiddenDiv" style="visibility:hidden"></div>

ohh and you will need jQuery

罗罗贝儿 2024-07-16 22:08:29

我用于 IE 中现有站点的一个简单解决方案(使用 jQuery,但如果您真的不太了解 JS,我可以使用 eventListener 代码回发)如下:

if (jQuery.browser.msie) {
  jQuery('#mySelect').focus(function() {
    jQuery(this).width('auto');
  }).bind('blur change', function() {
    jQuery(this).width('100%');
  });
};

当然,使用变量 (var cWidth = jQuery('#mySelect').width();) 来存储先前的宽度,但这就是我们的宽度按您的预期工作所需的全部。

A simple solution I used for an existing site in IE (using jQuery, but I can post back with eventListener code if you really don't know JS that well) is the following:

if (jQuery.browser.msie) {
  jQuery('#mySelect').focus(function() {
    jQuery(this).width('auto');
  }).bind('blur change', function() {
    jQuery(this).width('100%');
  });
};

Of course, use a variable (var cWidth = jQuery('#mySelect').width();) to store the previous width, but this is all that was required for ours to work as you'd expect.

没企图 2024-07-16 22:08:29

示例

function PopulateDropdown() {
    $.ajax({
        type: "POST",
        url: "../CommonWebService.asmx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("select[id^='MyDropDown']").empty();
            $.each(msg.d, function () {
                $("select[id^='MyDropDownSelect']").append($("<option></option>").val(this['IdIndexDataType']).html(this['DataTypeName']));
            }); 
            $("select[id^='MyDropDown']").css("width", "auto");  
        },
        error: function (e1) {
            alert("Error - " + e1.toString());
        }
    });
}

下面的代码将通过在将数据插入下拉列表后添加此代码来解决下拉列表宽度的问题。

$("select[id^='MyDropDown']").css("width", "auto");

Sample

function PopulateDropdown() {
    $.ajax({
        type: "POST",
        url: "../CommonWebService.asmx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("select[id^='MyDropDown']").empty();
            $.each(msg.d, function () {
                $("select[id^='MyDropDownSelect']").append($("<option></option>").val(this['IdIndexDataType']).html(this['DataTypeName']));
            }); 
            $("select[id^='MyDropDown']").css("width", "auto");  
        },
        error: function (e1) {
            alert("Error - " + e1.toString());
        }
    });
}

The below code will solve your problem of dropdownlist width by adding this code after insertion of Data to dropdownlist.

$("select[id^='MyDropDown']").css("width", "auto");
夜雨飘雪 2024-07-16 22:08:29

我创建了带有自动扩展功能的样式化选择元素,仅使用最少的 JS,基于数据属性隐藏的 CSS 伪元素

Array.from(document.querySelectorAll('.js-select-auto-expand'), (input) => {
  let parent = input.parentNode;
  
  function updateSize() {
    parent.dataset.selectAutoExpand = input.value
  }
  
  input.addEventListener('input', updateSize);
  
  updateSize();
});
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  padding: 2rem 4rem;
  line-height: 1.5;
  color: gray;
}

.article-test {
  line-height: 2.5;
}

.select-auto-expand {
  position: relative;
  display: inline-block;
  min-width: 2rem;
  width: auto;
  height: 30px;
  line-height: 28px;
  padding: 0 10px;
  vertical-align: baseline;
  border: 1px solid black;
  background-color: transparent;
  color: #fafafa;
  font-size: 1rem;
}
.select-auto-expand .select-auto-expand__select {
  position: absolute;
  top: 0px;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  min-width: 1em;
  height: 100%;
  margin: 0 2px;
  padding: 0 8px;
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  border-radius: 0;
  border: 0;
  background: transparent;
  font: inherit;
}
.select-auto-expand::after {
  content: attr(data-select-auto-expand);
  display: inline-block;
  width: 100%;
  min-width: 1em;
  white-space: pre-wrap;
  font: inherit;
  line-height: inherit;
  color: inherit;
  background: transparent;
  visibility: hidden;
  opacity: 0;
}
.select-auto-expand:focus-within {
  outline: 3px solid rgba(0, 0, 255, 0.3);
}
.select-auto-expand:focus-within input:focus {
  outline: none;
}
<form action="#" class="article-test">

  <p>
    Adipisci ipsum debitis quaerat commodi tenetur? Amet consectetur adipisicing elit. Lorem ipsum dolor sit, 
    <label class="select-auto-expand" for="pet-select">
      <select name="pets" id="pet-select" class="select-auto-expand__select js-select-auto-expand">
        <option value="select ...">select ...</option>
        <option value="sed qui">sed qui</option>
        <option value="veniam iste quis">veniam iste quis</option>
        <option value="ipsum debitis">ipsum debitis</option>
        <option value="officia excepturi repellendus aperiam">officia excepturi repellendus aperiam</option>
      </select>
    </label>
    veniam iste quis, sed qui non dolores. Porro, soluta. Officia excepturi repellendus aperiam cumque consectetur distinctio, veniam iste quis, sed qui non dolores. Adipisci ipsum debitis quaerat commodi tenetur?
  </p>

</form>

演示:
https://codepen.io/astro87/pen/dyZerdg?editors=0010

灵感来自:
https://filamentgroup.github.io/select-css/demo/
https://codepen.io/shshaw/full/bGNJJBE

I've created styled select element with auto expand, with just a minimal JS, based on data attribute and hidden CSS pseudo element.

Array.from(document.querySelectorAll('.js-select-auto-expand'), (input) => {
  let parent = input.parentNode;
  
  function updateSize() {
    parent.dataset.selectAutoExpand = input.value
  }
  
  input.addEventListener('input', updateSize);
  
  updateSize();
});
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  padding: 2rem 4rem;
  line-height: 1.5;
  color: gray;
}

.article-test {
  line-height: 2.5;
}

.select-auto-expand {
  position: relative;
  display: inline-block;
  min-width: 2rem;
  width: auto;
  height: 30px;
  line-height: 28px;
  padding: 0 10px;
  vertical-align: baseline;
  border: 1px solid black;
  background-color: transparent;
  color: #fafafa;
  font-size: 1rem;
}
.select-auto-expand .select-auto-expand__select {
  position: absolute;
  top: 0px;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  min-width: 1em;
  height: 100%;
  margin: 0 2px;
  padding: 0 8px;
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  border-radius: 0;
  border: 0;
  background: transparent;
  font: inherit;
}
.select-auto-expand::after {
  content: attr(data-select-auto-expand);
  display: inline-block;
  width: 100%;
  min-width: 1em;
  white-space: pre-wrap;
  font: inherit;
  line-height: inherit;
  color: inherit;
  background: transparent;
  visibility: hidden;
  opacity: 0;
}
.select-auto-expand:focus-within {
  outline: 3px solid rgba(0, 0, 255, 0.3);
}
.select-auto-expand:focus-within input:focus {
  outline: none;
}
<form action="#" class="article-test">

  <p>
    Adipisci ipsum debitis quaerat commodi tenetur? Amet consectetur adipisicing elit. Lorem ipsum dolor sit, 
    <label class="select-auto-expand" for="pet-select">
      <select name="pets" id="pet-select" class="select-auto-expand__select js-select-auto-expand">
        <option value="select ...">select ...</option>
        <option value="sed qui">sed qui</option>
        <option value="veniam iste quis">veniam iste quis</option>
        <option value="ipsum debitis">ipsum debitis</option>
        <option value="officia excepturi repellendus aperiam">officia excepturi repellendus aperiam</option>
      </select>
    </label>
    veniam iste quis, sed qui non dolores. Porro, soluta. Officia excepturi repellendus aperiam cumque consectetur distinctio, veniam iste quis, sed qui non dolores. Adipisci ipsum debitis quaerat commodi tenetur?
  </p>

</form>

Demo:
https://codepen.io/astro87/pen/dyZerdg?editors=0010

Inspired by:
https://filamentgroup.github.io/select-css/demo/
https://codepen.io/shshaw/full/bGNJJBE

年华零落成诗 2024-07-16 22:08:29

我改进了 cychan 的解决方案,如下所示:

<html>
<head>

<style>
    .wrapper{
        display: inline;
        float: left; 
        width: 180px; 
        overflow: hidden; 
    }
    .selectArrow{
        display: inline;
        float: left;
        width: 17px;
        height: 20px;
        border:1px solid #7f9db9;
        border-left: none;
        background: url('selectArrow.png') no-repeat 1px 1px;
    }
    .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
    .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>

<script language="javascript">
    $(document).ready(function(){
        $('#w1').wrap("<div class='wrapper'></div>");
        $('.wrapper').after("<div class='selectArrow'/>");
        $('.wrapper').find('select').mousedown(function(){
            $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).parent().next().addClass('selectArrow-mouseover');
        }, function(){
            $(this).parent().next().removeClass('selectArrow-mouseover');
        });

        $('.selectArrow').click(function(){
            $(this).prev().find('select').focus();
        });

        $('.selectArrow').mousedown(function(){
            $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).addClass('selectArrow-mouseover');
        }, function(){
            $(this).removeClass('selectArrow-mouseover');
        });
    });

</script>
</head>
<body>
    <select id="w1">
       <option value="0">AnyAnyAnyAnyAnyAnyAny</option>
       <option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
    </select>

</body>
</html>

CSS 类中使用的 PNG 是上传到这里...

并且您仍然需要 JQuery...

I improved the cychan's solution, to be like that:

<html>
<head>

<style>
    .wrapper{
        display: inline;
        float: left; 
        width: 180px; 
        overflow: hidden; 
    }
    .selectArrow{
        display: inline;
        float: left;
        width: 17px;
        height: 20px;
        border:1px solid #7f9db9;
        border-left: none;
        background: url('selectArrow.png') no-repeat 1px 1px;
    }
    .selectArrow-mousedown{background: url('selectArrow-mousedown.png') no-repeat 1px 1px;}
    .selectArrow-mouseover{background: url('selectArrow-mouseover.png') no-repeat 1px 1px;}
</style>
<script language="javascript" src="jquery-1.3.2.min.js"></script>

<script language="javascript">
    $(document).ready(function(){
        $('#w1').wrap("<div class='wrapper'></div>");
        $('.wrapper').after("<div class='selectArrow'/>");
        $('.wrapper').find('select').mousedown(function(){
            $(this).parent().next().addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).parent().next().removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).parent().next().addClass('selectArrow-mouseover');
        }, function(){
            $(this).parent().next().removeClass('selectArrow-mouseover');
        });

        $('.selectArrow').click(function(){
            $(this).prev().find('select').focus();
        });

        $('.selectArrow').mousedown(function(){
            $(this).addClass('selectArrow-mousedown').removeClass('selectArrow-mouseover');
        }).
        mouseup(function(){
            $(this).removeClass('selectArrow-mousedown').addClass('selectArrow-mouseover');
        }).
        hover(function(){
            $(this).addClass('selectArrow-mouseover');
        }, function(){
            $(this).removeClass('selectArrow-mouseover');
        });
    });

</script>
</head>
<body>
    <select id="w1">
       <option value="0">AnyAnyAnyAnyAnyAnyAny</option>
       <option value="1">AnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAnyAny</option>
    </select>

</body>
</html>

The PNGs used in css classes are uploaded here...

And you still need JQuery.....

┾廆蒐ゝ 2024-07-16 22:08:29

您可以尝试仅使用 css 来解决。 通过添加类来选择

select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}

更多参考 列表框特定项目(选项)HTML 中的样式

多选列表框

you can try and solve using css only. by adding class to select

select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}

for more reference List Box Style in a particular item (option) HTML

Multi Select List Box

几度春秋 2024-07-16 22:08:29

这是这里最好的答案。 它是纯粹的现代原生 JavaScript

DOM 中不需要 JQuery 或永久不可见的

其他普通 JavaScript 答案在所有情况下都无法 100% 正确运行。 此方法考虑了很多因素,例如fontpaddingborder等。

function resize(event) {
  const fakeEl = document.createElement('select');
  const option = event.target.options[event.target.selectedIndex];

  fakeEl.style.visibility = 'hidden';
  fakeEl.style.position = 'absolute';
  fakeEl.style.top = '-9999px';
  fakeEl.style.left = '-9999px';
  fakeEl.style.width = 'auto';
  fakeEl.style.font = window.getComputedStyle(event.target).font;
  fakeEl.style.padding = window.getComputedStyle(event.target).padding;
  fakeEl.style.border = window.getComputedStyle(event.target).border;

  const fakeOption = document.createElement('option');
  fakeOption.innerHTML = option.innerHTML;
  fakeEl.appendChild(fakeOption);
  document.body.appendChild(fakeEl);

  event.target.style.width = fakeEl.getBoundingClientRect().width + 'px';
  fakeEl.remove();
}

for (let e of document.querySelectorAll('select.autoresize')) {
  e.onchange = resize;
  e.dispatchEvent(new Event('change'));
}
<select class='autoresize'>
  <option>Foo</option>
  <option>FooBar</option>
  <option>FooBarFooBarFooBar</option>
</select>

This is the best answer here. It's pure modern vanilla JavaScript.

There's no need for JQuery or a permanent invisible <select> within your DOM:

None of the other vanilla JavaScript answers worked 100% correctly in all cases. This method takes many things into account such as font, padding, border, etc.

function resize(event) {
  const fakeEl = document.createElement('select');
  const option = event.target.options[event.target.selectedIndex];

  fakeEl.style.visibility = 'hidden';
  fakeEl.style.position = 'absolute';
  fakeEl.style.top = '-9999px';
  fakeEl.style.left = '-9999px';
  fakeEl.style.width = 'auto';
  fakeEl.style.font = window.getComputedStyle(event.target).font;
  fakeEl.style.padding = window.getComputedStyle(event.target).padding;
  fakeEl.style.border = window.getComputedStyle(event.target).border;

  const fakeOption = document.createElement('option');
  fakeOption.innerHTML = option.innerHTML;
  fakeEl.appendChild(fakeOption);
  document.body.appendChild(fakeEl);

  event.target.style.width = fakeEl.getBoundingClientRect().width + 'px';
  fakeEl.remove();
}

for (let e of document.querySelectorAll('select.autoresize')) {
  e.onchange = resize;
  e.dispatchEvent(new Event('change'));
}
<select class='autoresize'>
  <option>Foo</option>
  <option>FooBar</option>
  <option>FooBarFooBarFooBar</option>
</select>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文