用省略号设置下拉列表选项

set dropdown list option with ellipses

本文关键字:选项 下拉列表 设置 省略号      更新时间:2023-09-26

如果单击省略号,我想在下拉列表选项中添加省略号以查看完整的选项值

例如,下拉列表看起来像这个

<select id ="id">
        <option>One - A long text need to be cut off with ellipsis</option>
        <option>Two - A long text need to be cut off with ellipsis</option>
</select>

我期望输出如下

一个-一个长选项。。。。二——一个长期的选择。。。。

当单击省略号时,可以看到完整的选项值,如一-需要用省略号截断长文本

请看我迄今为止做的代码

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style>
select {
    width:200px;
}
</style>
<script>
$(document).ready(function() {
var maxLength = 20;
    $('#example > option').text(function(i, text) {
    if (text.length > maxLength) {
        return text.substr(0, maxLength) + '...';  
        }
    });
});
</script>
</head>
<body>
<select name="example" id="example">
    <option value="">John Smith,1019 Your Company PO Box 7169 Poole BH15 9EL</option>
    <option value="">91 Western Road,Brighton PO Box 7169 East Sussex England BN1 2NWL</option>
    <option value="">John Smith,1019 Your Company PO Box 7169 Poole BH15 9EL</option>
</select>
</body>
</html>

请帮助我获得上述的预期结果

这是我为您提供的问题解决方案。

这是一种变通方法,目标是椭圆选择值,并在显示选项时显示孔文字。因此用户可以读取选项值。

$(document).ready(function () {
            $('div.viewport').text($('#example')[0].textContent);
            $('#example').change(function () {
                $('div.viewport').text($("option:selected", this).text());
            });            
        });
 select, .container {
            width: 100px;
            z-index: 2;
            position: relative;
        }
        select {
            color: transparent;
            background: none;
        }
        .container {
            position: relative;
        }
        .viewport {
            position: absolute;
            width: 80%;
            height: 100%;
            z-index: 1;
            overflow: hidden;
            white-space: nowrap;
            -ms-text-overflow: ellipsis;
            -o-text-overflow: ellipsis;
            text-overflow: ellipsis;
            font-size: 14px;
            padding: 3px;
        }
        option {
            color: black;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
        <div class="viewport"></div>
        <select name="example" id="example">
            <option value="">This is some longggggggggggggggggggggggggggggggg text</option>
            <option value="">Short Text</option>
            <option value="">This is some really,really long text text and text</option>
        </select>
    </div>

这是设置标题显示选项文本的代码

$(function(){
              $("select option").attr( "title", "" );
              $("select option").each(function(i){
                this.title = this.text;
              })
            });
            $("select").tooltip({
                left:25
            });

在这里,您可能找不到跨浏览器兼容的解决方案。由于选择选项元素不能像往常一样具有样式。因此,如果你能从语法上做到这一点,那将是安全的。