为' <select> ' s的选定选项显示不同的文本
Show a different text for the selected option for `<select>`s
我希望<select>
中显示的文本与所选<option>
的文本不同。我的宽度有限,所以如果我在<option>
中显示所有文本,那么一些文本将被截断。
例如,如果我的标记是:
<select>
<option>Open (some description)</option>
<option>Closed (a bunch of text</option>
</select>
当第一个选项被选中时,我想只显示单词"打开"以节省空间。我不能只使用Javascript来替换文本,因为如果用户打开select,他们就会看到缩短的文本。
是否有办法做到这一点使用<select>
标签(即不使用自定义选择器)?
使用JS,您可以添加focus
和blur
事件侦听器,它们可以修改option
s的文本:
function focus() {
[].forEach.call(this.options, function(o) {
o.textContent = o.getAttribute('value') + ' (' + o.getAttribute('data-descr') + ')';
});
}
function blur() {
[].forEach.call(this.options, function(o) {
console.log(o);
o.textContent = o.getAttribute('value');
});
}
[].forEach.call(document.querySelectorAll('.shortened-select'), function(s) {
s.addEventListener('focus', focus);
s.addEventListener('blur', blur);
blur.call(s);
});
<select class="shortened-select">
<option value="Open" data-descr="some description"></option>
<option value="Closed" data-descr="a bunch of text"></option>
</select>
您可以创建第二个select
元素,它具有缩写选项。在默认情况下显示它,并隐藏select
元素与非缩写选项。
当缩略的select
悬停时,显示另一个select
元素
当你改变一个选项时,将缩写的select
元素的selectedIndex
设置为匹配,这将使两个元素保持同步:
document.getElementById('s2').addEventListener('input', function() {
document.getElementById('s1').selectedIndex= this.selectedIndex;
});
#s1 {
position: absolute;
}
#s2 {
display: none;
}
#s2:hover, #s1:hover + select {
position: relative;
display: inline;
}
<select id="s1">
<option>Open</option>
<option>Closed</option>
</select>
<select id="s2">
<option>Open (some description)</option>
<option>Closed (a bunch of text</option>
</select>
不使用javascript的最佳方法是:
<select size="5">
<option title="(some description)">Open</option>
<option title="(a bunch of text)">Closed</option>
</select>
当鼠标悬停在
选项上时, title
将显示为工具提示。
小提琴:http://jsfiddle.net/1ywv0uab/
你可以试试CSS伪元素。因为它们只是样式,它们不影响select
的值,所以当select
关闭时,插入的文本将不会显示。
option:after {
content: ' (' attr(data-descr) ')';
}
<select>
<option data-descr="some description">Open</option>
<option data-descr="a bunch of text">Closed</option>
</select>
如果你想让select
缩小到短文本的宽度,你只能在:focus
显示伪元素。
select:focus > option:after {
content: ' (' attr(data-descr) ')';
}
<select>
<option data-descr="some description">Open</option>
<option data-descr="a bunch of text">Closed</option>
</select>
相关文章:
- 从服务器获取数据并在选择控件中使用ng选项无法显示选项
- 在iPad上,如何通过Javascript事件在选择元素上设置focus()而不显示选项
- Javascript测试-使用Array.prototype以随机顺序显示选项
- 显示选项卡后向上滚动
- 使用 jQuery UI 选择菜单中选择中的隐藏/显示选项
- 无法使用 jquery 显示选项卡内容
- 如何在 angularjs 材料设计中显示选项卡标题中心对齐
- JavaScript 选择列表,循环显示选项
- 我制作了自己的jquery选项卡版本,但我需要外部链接来显示选项卡内容和样式原始导航
- 寻找跨浏览器解决方案来突出显示选项卡
- 请求方法显示选项而不是开机自检
- 如何在“挖空.js”中单击后显示选项默认标题
- 有条件地在带有角度的选择中显示选项
- 如何使用 Twitter Bootstrap 3 显示选项卡内容
- 高图表折线图中的单击并保持突出显示选项
- 火狐扩展 - >获取显示选项卡的内容
- 使用 javascript 在下拉列表中显示选项的键和值
- AngularJS Autocomplete未显示选项
- 我希望根据使用jquery单击的选项卡来显示选项卡内容
- jQuery在页面刷新时选择排序更改显示选项.什么'正在发生