javascript - 如何在用户想要选择一个选项后增加/减少 'select' 选项宽度

标签 javascript php jquery html css

我有一个选择框,我在其中硬编码了宽度。我想要根据所选文本的宽度。如果文本很长则宽度会自动扩展,如果文本很短则会根据它进行调整。这是我的代码。

.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/

相关文章:

php - PHP函数中使用的变量会在函数执行后自动取消设置吗?

php - MySQL加载文件和撇号

javascript - 如何将代码应用到动态创建的元素

javascript - 如何在选择文件后禁用 Dropzone.js?

javascript - 如何将输入中的 0 替换为个位数?

javascript - Lodash 如何使用双键将 _.grouby 一组数据加倍并 _.chain() 它们?

javascript - 在 jQuery Mobile 中动态创建可折叠集

javascript - 如何强制用户的鼠标滚动操作到 div,而不是 body?

javascript - 如何在 PHP CRUD 编辑操作中获取日期和复选框数据

jquery - 从 jquery 调用 MVC 操作并处理重定向或返回的部分 View