下拉选择和向下箭头automove参考文本长度

时间:2016-03-14 20:34:51

标签: javascript jquery css

我有一个透明下拉选择向下箭头。问题是,无论文本是短还是长,箭头始终与文本位置相同:

enter image description here

正如您在上面所看到的,文本和箭头之间存在很大差距,但必须要有更长的文本才能适应。 (看起来不太好)

我想以两种方式完成此操作(这取决于网站的哪一侧我会有选择框):

1)自动将箭头向左移动,如同文本总是7px一样(无论文字是短还是长)。

enter image description here

2)自动将文本向右移动,如7px,始终从箭头开始(无论文本是短还是长)。

enter image description here

所以,这是我的代码(在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>	

1 个答案:

答案 0 :(得分:0)

(我会评论,但我的分数太低了)

您应该问自己是否真的需要这种动态宽度。这不是用户习惯的原因,可能会降低用户体验。

我不相信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组合制作“您自己的选择框”。 Google custom select可以获得一些想法。祝你好运!