[英]How to display only part of the option text in a select when it is not dropped down
我在网页上有一个下拉选择框来选择(例如)客户代码 - 这是在现有数据库上用于代表客户的短代码。
为了使用户界面更易于使用,我希望在下拉列表中显示更多信息,而不仅仅是代码——例如客户全名。
但是,由于空间原因,我不希望客户名称在没有下拉的情况下显示在选择框中,而只是代码。
谁能建议一个相当简单的方法来做到这一点? 我目前在项目中使用 jquery,如果有帮助的话。
To summarise - when the select is closed, I want to just display the customer short code. 当它被下拉时,我想在每个选择选项中显示代码和全名。
我想到我可以通过更改选项文本来做到这一点,具体取决于下拉菜单是否打开。 但是,我似乎找不到在下拉菜单打开和关闭时触发的事件。
那是不可能的。 我建议您构建一个自定义 droprown,例如:
<div class="dropdown">
<span class="dropdown-label">1234</span>
<select>
...
</select>
</div>
在这种情况下,使用 CSS,您可以将span
放在select
顶部并使用pointer-events: none
这样当用户单击span
, select
(在它下面)接收单击并打开。 然后只需监听选择的change
事件以在选择选项时更新标签,无论您想显示什么。
使用$('.dropdown option:selected').text("text")
设置所选下拉项的文本,并在将客户代码与名称分开的值(可能是空格)上使用 javascript string.split()
。
我很喜欢Gabriel的答案,但我对 CSS 没有足够的经验,所以我决定用一个非常有用的例子来展示完整的答案:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<style>
#the_td_of_time_zone{
position: relative;
width: 50px;
}
#the_span{
/*To align text horizontally and vertically inside the parent*/
text-align: center;
vertical-align: middle;
line-height: 20px; /* The same as your parent height */
pointer-events: none; /*allow the click to pass through the element*/
position: absolute; /*To help overlap Zone with dropdown*/
z-index: 100; /*To put the Zone on top of the dropdown*/
background-color: #006699; /*To match with Admin Menu background*/
height: 20px;
width: 100%;
left: 0px;
text-decoration: None;
color: #FFFFFF;
font-weight: bold;
font-size: 12px;
}
}
#the_select{
position: absolute;
}
</style>
<div id="the_td_of_time_zone">
<span id="the_span">Time Zone</span>
<select id="the_select">
<option>uno</option>
<option>dos</option>
</select>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.