HTML下拉列表自动宽度调整 [英] HTML Dropdown Auto-Width Adjust
问题描述
我创建了一个下拉菜单,该下拉菜单会根据选择的内容调整大小。我使用以下stackoverflow答案作为灵感来调整下拉菜单的大小: https://stackoverflow.com/a/20091985/3166468
I've created a dropdown that has issues resizing according to what's selected. I'm using the following stackoverflow answer as inspiration to resize my dropdown: https://stackoverflow.com/a/20091985/3166468
由于某种原因,尽管会发生调整大小,但调整大小总是太大或太小。这是jsFiddle: https://jsfiddle.net/yadhwb97/3/
For some reason, although the resizing happens, it always resizes either too much or too little. Here's the 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);
});
});
选择下拉选项后,您会看到它的大小调整得太大还是太小。如何使调整大小正常工作?
When you select the dropdown options, you'll see how it resizes either too much or too little. How can I make the resizing work correctly?
推荐答案
问题是隐藏的下拉列表具有diff字体大小。
将 font-size:16px;
添加到 #width_tmp_select
并应立即运行。
the problem is your hidden dropdown has diff font size.
add font-size: 16px;
to #width_tmp_select
and should work now.
$(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>
这篇关于HTML下拉列表自动宽度调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!