HTML Dropdown Auto-Width Adjust

2019-08-02 03:45发布

问题:

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

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/

This is the 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>

And this is the 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?

回答1:

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>



回答2:

With CSS my friend!! Please rep me :)

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