我有一个带有向下箭头的透明下拉选择。问题是无论文本是短还是长,箭头始终位于文本的相同位置,如下所示:
正如您在上面看到的,文本和箭头之间有一个很大的间隙,但它必须适合较长的文本。 (看起来不太好)
我想通过两种方式完成此操作(这取决于我将在网站的哪一侧设置选择框):
1) 像往常一样自动将箭头向左移动距文本 7px(无论文本是短还是长)。
2) 自动将文本从箭头向右移动 7px(无论文本是短还是长)。
所以,这是我的代码(最好在 link 下查看):
HTML:
<div class="dropDownArrow"></div>
<select class="selectClass">
<option>short</option>
<option>very long text</option>
<option>long test</option>
</select>
CSS:
.dropDownArrow {position: absolute; left: 140px; top: 20px; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #7c7c7c;}
.selectClass {-webkit-appearance: none; -webkit-border-radius: 0; -moz-appearance: none; border: none; background: transparent; height: 30px; width: 140px; font-size: 18px; padding-left: 80px; position: absolute; color: #7c7c7c; outline: none;}
select option {background: #EFEFEF; color:#7c7c7c;}
select:-moz-focusring {color: transparent; text-shadow: 0 0 0 #7c7c7c;}
如何修复代码?最好是只使用 CSS,但我不确定如果没有 JS(或 jQuery)是否可行。
.dropDownArrow {position: absolute; left: 140px; top: 20px; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #7c7c7c;}
.selectClass {-webkit-appearance: none; -webkit-border-radius: 0; -moz-appearance: none; border: none; background: transparent; height: 30px; width: 140px; font-size: 18px; padding-left: 0px; position: absolute; color: #7c7c7c; outline: none;}
select option {background: #EFEFEF; color:#7c7c7c;}
select:-moz-focusring {color: transparent; text-shadow: 0 0 0 #7c7c7c;}
<div class="dropDownArrow"></div>
<select class="selectClass">
<option>short</option>
<option>very long text</option>
<option>long test</option>
</select>
最佳答案
(我会评论,但我的分数太低了)
您应该问问自己是否真的需要这个动态宽度。这不是用户习惯的,并且可能会降低用户体验。
我不认为这对 CSS 是可行的。对于大多数情况,您可以使用 CSS 伪元素,例如 :before
, 但这不适用于 <select>
.
这是一个 "quick 'n dirty fiddle"给你一个 JS 的例子:
$(function() {
$(".selectClass").on("change", function() {
var $this = $(this);
var $arrow = $("#dropDownArrow1");
var dynamicWidth = $this.val().length * 10; // May work for most cases or not
var dropdownArrowStaticArmLength = -8;
if (dynamicWidth <= 50) // one of the "not"s
dynamicWidth = 65;
$this.css("width", dynamicWidth + "px");
$arrow.css("left", dynamicWidth + dropdownArrowStaticArmLength + "px");
});
$(".selectClass").change();
});
文本长度与框宽度之间存在一些缺陷 - 这不是生产代码,只是一个示例。
更好的方法是结合 JS 和 CSS 制作“您自己的选择框”。谷歌custom select
得到一些想法。祝你好运!
关于javascript - 下拉选择和向下箭头汽车引用文本长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35997537/