为`& lt; select& gt; s的所选选项显示不同的文本 [英] Show a different text for the selected option for `<select>`s
问题描述
我希望< select>
中显示的文本与所选< option>
的文本不同.我的宽度有限,因此,如果我在< option>
中显示所有文本,则会截断一些文本.
I want the text that's displayed in the <select>
to be different from the selected <option>
's text. I have limited width to work with, so if I display all the text in the <option>
, then some text with be cut off.
例如,如果我的标记是这样:
For example, if my markup is this:
<select>
<option>Open (some description)</option>
<option>Closed (a bunch of text</option>
</select>
选择第一个选项时,我只想显示打开"一词以节省空间.我不能只使用Javascript替换文本,因为如果用户打开选择,那么他们会看到缩短的文本.
When the first option is selected, I want to show only the word "Open" to save space. I can't just use Javascript to replace the text because if the user opens the select, then they'll see the shortened text.
是否可以使用< select>
标签(即不使用自定义选择器)来执行此操作?
Is there a way to do this using the <select>
tag (i.e. without using a custom selector)?
推荐答案
使用JS,您可以添加 focus
和 blur
事件监听器,以修改选项
s:
Using JS, you can add a focus
and blur
event listeners which modify the text of the 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>
这篇关于为`& lt; select& gt; s的所选选项显示不同的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!