【问题标题】:How to right align some part of text in <option> in <select>如何在 <select> 中的 <option> 中右对齐文本的某些部分
【发布时间】:2018-11-10 09:32:36
【问题描述】:

这是目前的样子

我期待这个

代码

   <select class="form-control">
        <option value="1123x1">S\J [1123]</option>
        <option value="562x1">Rib / Int. [562]</option>
        <option value="1123x3">Fleece [1123]</option>
    </select>

还需要 select2 的建议。

【问题讨论】:

  • 这样试试
  • 我不认为只有 css 才有可能你为什么不试试下拉列表
  • 字符长度并不总是相同,因此对齐中断:'(
  • 怎么做? @Viira

标签: html css jquery-select2


【解决方案1】:

这是实现这一目标的一种方法:

使用select2的配置选项:templateResulttemplateSelectionescapeMarkup,可以根据需要操作下拉列表。

我在这里使用示例数据:

$('#example').select2({
		data: [
    	{id: 'test1', text: 'January', subText: "Test1"},
      {id: 'test2', text: 'February', subText: "Test2"},
    	{id: 'test3', text: 'March', subText: "Test3"}      
    ],
    placeholder: 'Select a month',
    escapeMarkup: function (markup) {
    	return markup;
    },
    templateResult: function (d) {
    	return '<span>'+d.text+'</span><span class="pull-right subtext">'+d.subText+'</span>';
    },
    templateSelection: function (d) {
    	return d.text + ' ( ' + d.subText + ')';
    }
}).val('test2').trigger('change');
.pull-right {
  float: right!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>

<select id="example" multiple="multiple" style="width: 300px"></select>

快速解释:

  1. templateSelection 是列表的呈现方式。
  2. templateResult 是选择选项的显示方式(尝试选择一个选项,您会看到它是如何工作的)
  3. escapeMarkup,简而言之,就是让 select2 知道您在 templateResulttemplateSelection 选项中使用 HTML。
  4. 应用pull-right(对应CSS:float: right;将潜台词右移。

您可以根据需要操作选项。我只是想展示它是如何完成的。希望这会有所帮助。

【讨论】:

  • 感谢您提供了一个不错的解决方案,它正在工作。但是如何给选项赋值呢?
  • 您可以使用.val(&lt;value&gt;)设置值并默认触发更改.trigger('change')。用一个例子编辑了帖子。
【解决方案2】:

一定有更好的解决方案。这是我试图解决你的问题

 <select class="form-control">
        <option value="1123x1">S\J &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[1123]</option>
        <option value="562x1">Rib / Int.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [562]</option>
        <option value="1123x3">Fleece&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1123]</option>
    </select>

【讨论】:

  • 它会使列表看起来就像 OP 提供的第一个屏幕截图一样,不是吗?
  • 我正在从 PHP 脚本生成&lt;option&gt;s,可能有数百个选项
  • 是的,但是如果列表是静态的,那么他可以调整   的数量得到想要的结果。
  • 好的,让我想想一些解决方法。这是相当棘手的,有点难以实现
  • @pravinnavle 请参阅我上面的答案,它使用 select2 的 API 选项将文本向右对齐并且没有固定空格(以防万一)
猜你喜欢
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
相关资源
最近更新 更多