[英]HTML drop-down change size when shorter option selected
I have this bit of HTML:我有一点 HTML:
<select name="tables" id="tables"> <option value="random">Random</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select>
My problem is that "Random" is has a lot more characters than "1", "2",or "3".我的问题是“随机”的字符比“1”、“2”或“3”多得多。 When I select, lets say, "2", the box is still the same size as "Random" (try it above).当我 select 说“2”时,盒子的大小仍然与“随机”相同(在上面尝试)。 Can I make the size automatically change as the input changes?我可以让尺寸随着输入的变化而自动变化吗? Even if the number goes to 135?即使数字达到135? I'm not new to JavaScript either, so if there is a way to achieve it using JS, I'd be grateful!我对 JavaScript 也不是新手,所以如果有办法使用 JS 实现它,我将不胜感激!
You can create a hidden view to store the selected item and get the width corresponding to it and then set the width to your selected view.您可以创建一个隐藏视图来存储所选项目并获取与其对应的宽度,然后将宽度设置为您选择的视图。 Check the below example.检查以下示例。
$(document).ready(function() { $('#resizing_select').change(function(){ $("#width_tmp_option").html($('#resizing_select option:selected').text()); $(this).width($("#width_tmp_select").width()); }); });
#resizing_select { width: 80px; } #width_tmp_select{ display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="resizing_select"> <option>random</option> <option>1</option> <option>2</option> <option>2</option> </select> <select id="width_tmp_select"> <option id="width_tmp_option"></option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.