如何增加/减少'选择'用户想要选择一个选项后的选项宽度
How to increase/decrease 'select' option width after the user wants to select an option
我有一个选择框,我硬编码与宽度。我想根据所选文本的宽度。如果文本很长,那么宽度会自动扩展,如果文本很短,那么它会根据它进行调整。这是我的代码。
.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>
如果你能找到长度,你可以根据你的字符改变宽度。
查找
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>
Demo
$(document).ready(function()
{
$("#discoverselect").change(function()
{
$(this).width(textWidth($(this).find("option:selected").text())+20);
}).trigger("change");
});
function textWidth(str)
{
var span = $("<span style='white-space: nowrap;'>"+str+"</span>");
$("body").append(span);
var width = span.width();
span.remove();
return width;
};
相关文章:
- 使用此选项选择父类内部的类
- 更新:仅根据单选按钮和所选选项选择特定项目
- 使用PHP通过HTML表单选项选择器过滤MYSQL结果
- ng-单击在IE中不起作用的选项选择Angularjs
- 从选项选择中删除值
- On为<选项>选择等效项
- 用户界面先前选择的选项选择更改
- 使用ng重复或ng选项和删除空白选项选择长方体角度
- 在HTML5、CSS、JavaScript中添加选项选择器,类似于移动应用程序中的选项设置
- 输入:选中,选项:选择选择器
- 根据使用angularjs从下拉菜单中选择的选项选择适当的复选框
- 如何根据 html 中的选项/选择重定向用户(单击按钮后)
- 使用ng选项选择中的ng选项进行过滤器下拉列表
- 如何设置选项选择的值
- 如何搜索长下拉选项/选择列表
- jQuery - 根据下拉选项选择列出结果
- 从选项选择单击时打开 2 个 URL
- 在 Angular JS 中为 ng 选项选择默认值
- 下拉选项选择的操作
- 通过单击单选按钮清除所有选项选择条目