纯CSS实现HTML Select元素浮动标签的问题求助
纯CSS实现HTML Select元素浮动标签的问题求助
最近我在给select元素做浮动标签效果,需求很明确:当点击聚焦这个下拉框时,标签要平滑浮到它上方;如果选中了某个选项,标签就一直保持在上方;要是没选任何选项(比如切回空选项),标签就回到原来的位置。
但现在遇到个头疼的问题——当我选中一个选项后,标签居然会掉下来盖在选中的选项文字上,没法保持浮动状态。
我知道给select绑定onclick事件手动设置value属性能解决,但我想找一个纯CSS的解决方案,而且要兼容移动端。那种给select加onclick="this.setAttribute('value', this.value);"的方法我觉得不够优雅,不想用。
以下是我目前写的代码,麻烦大家帮忙看看怎么调整才能实现需求:
CSS代码
.floating-label { position:relative; margin-bottom:20px; } .floating-select { font-size:14px; padding:4px 4px; display:block; width:100%; height:30px; background-color: transparent; border:none; border-bottom:1px solid #757575; } .floating-select:focus { outline:none; border-bottom:2px solid #5264AE; } label { color:#999; font-size:14px; font-weight:normal; position:absolute; pointer-events:none; left:5px; top:5px; transition:0.2s ease all; -moz-transition:0.2s ease all; -webkit-transition:0.2s ease all; } .floating-select:focus ~ label , .floating-select:not([value=""]):valid ~ label { top:-18px; font-size:14px; color:#5264AE; } /* active state - 这段代码好像有问题,暂时没起作用 */ .floating-select:focus ~ .floating-select:focus ~ { width:50%; } *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /* active state */ .floating-select:focus ~ { -webkit-animation:inputHighlighter 0.3s ease; -moz-animation:inputHighlighter 0.3s ease; animation:inputHighlighter 0.3s ease; }
HTML代码
<div class="floating-label"> <select class="floating-select"> <option value=""></option> <option value="1">Item1</option> <option value="2">Item2</option> <option value="3">Item3</option> <option value="4">Item4</option> <option value="5">Item5</option> </select> <label>Select</label> </div>
备注:内容来源于stack exchange,提问作者suzkirch
相关产品推荐
相关产品推荐

