【问题标题】:HTML Dropdown Auto-Width AdjustHTML下拉自动宽度调整
【发布时间】:2017-08-06 15:00:28
【问题描述】:

我创建了一个下拉菜单,该下拉菜单在根据所选内容调整大小时出现问题。我使用以下 stackoverflow 答案作为调整下拉列表大小的灵感:https://stackoverflow.com/a/20091985/3166468

由于某种原因,尽管发生了调整大小,但它总是调整得过大或过小。这是 jsFiddle:https://jsfiddle.net/yadhwb97/3/

这是 HTML:

<div class="dropdown">
  <select id="real_dropdown">
    <option disabled="">Options</option>
    <option value="long">Something super long in here</option>
    <option value="short">Short</option>
  </select>
</div>
<select id="width_tmp_select">
  <option id="width_tmp_option"></option>
</select>

这是 jQuery:

$(document).ready(function() {
  $('.dropdown').change(function(){
    $("#width_tmp_option").html($('.dropdown option:selected').text()); 
    $(this).width($("#width_tmp_select").width()+30);  
  });
});

当您选择下拉选项时,您会看到它的大小调整得过大或过小。如何使调整大小正常工作?

【问题讨论】:

  • 您可以随时增加width value,即使用其他东西代替+30。但是,获得准确的解决方案可能有点棘手。您必须使用namewidth 将每个选项的初始宽度存储在一个对象中,然后在更改时根据选择拉取值并设置宽度。目前,您可以在选择 long 选项时将宽度设置为 280,但您需要考虑以后添加的未来/其他选项。
  • 检查我的解决方案,它运行良好:stackoverflow.com/a/55343177/1243247

标签: html css drop-down-menu


【解决方案1】:

问题是您隐藏的下拉菜单的字体大小不同。 将font-size: 16px; 添加到#width_tmp_select,现在应该可以使用了。

$(document).ready(function() {
  $('.dropdown').change(function(){
    $("#width_tmp_option").html($('.dropdown option:selected').text()); 
    $(this).width($("#width_tmp_select").width());  
  });
});
.dropdown {
  width: 280px;
  overflow: hidden;
  background: url(https://secure.echobox.com/img/dropdown_arrow.png) no-repeat right transparent;
  border: 1px solid black;
  white-space: nowrap;
  background-size: 18px 5px;
}

.dropdown select {
  width: 100%;
  background: transparent;
  font-size: 16px;
  border: 0;
  border-radius: 0;
  -webkit-appearance: none;
  -moz-appearance: none;
  font-family: "proxima-nova", Helvetica, Arial, sans-serif;
  white-space: nowrap;
  color: #56646E;
}

#width_tmp_select{
  display : none;
	font-size: 16px;
} 
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>

<h2>
This "custom" dropdown doesn't resize correctly.
</h2>
<div class="dropdown">
  <select id="real_dropdown">
    <option disabled="">Options</option>
    <option value="long">Something super long in here</option>
    <option value="short">Short</option>
  </select>
</div>
<select id="width_tmp_select">
  <option id="width_tmp_option"></option>
</select>

【讨论】:

【解决方案2】:

使用 CSS 我的朋友!请代表我:)

#real_dropdown {
  width: 100px;
  min-width: 100px;
  max-width: 200px;
}
#width_tmp_select {
  width: 100px;
  min-width: 100px;
  max-width: 200px;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2010-09-14
    • 2011-05-17
    • 2016-06-14
    • 2013-02-07
    • 2012-11-19
    相关资源
    最近更新 更多