我有一个选择框,我在其中硬编码了宽度。我想要根据所选文本的宽度。如果文本很长则宽度会自动扩展,如果文本很短则会根据它进行调整。这是我的代码。
.post-select {
border:none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
<select id="discoverselect" class="post-select">
<option>All Sports</option>
<option>OCR</option>
<option>Triathlon</option>
<option>Running and Marathon</option>
<option>Ultramarathon</option>
<option>Cycling</option>
</select>
最佳答案
if you can find the length you can change the width according to your characters.
To find the length
function textWidth(str){
var span = $("<span>"+str+"</span>");
$("body").append(span);
var width = span.width();
span.remove();
return width;
};
$(document).ready(function(){
$("#discoverselect").change(function(){
$(this).width(textWidth($(this).find("option:selected").text()));
}).trigger("change");
});
function textWidth(str){
var span = $("<span>"+str+"</span>");
$("body").append(span);
var width = span.width();
span.remove();
return width;
};
.post-select {
border:none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="discoverselect" class="post-select">
<option>All Sports</option>
<option>OCR</option>
<option>Triathlon</option>
<option>Running and Marathon</option>
<option>Ultramarathon</option>
<option>Cycling</option>
</select>
关于javascript - 如何在用户想要选择一个选项后增加/减少 'select' 选项宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917439/