简体   繁体   English

如何使用CSS样式选择选项

[英]How to style select option with css

I need to style my select with css, so it looks like the image below, there is 2 things i cant figure out, when option is selected remove the classic blue background, how to indent the text, text-indent is not working for me, and how to lower the option box. 我需要用css设置我的选择的样式,所以它看起来像下面的图片,有两件事我无法弄清楚,当选择选项时,删除经典的蓝色背景,如何使文本缩进,text-indent对我不起作用,以及如何降低选项框。

 <select name="txtCountry">
    <option>Select Country</option>
    <option value="1">Georgia</option>
    <option value="2">Afghanistan</option>
</select>

在此处输入图片说明

Select tags are near-enough impossible to customise, and are at the mercy of your browser as to how they are styled (albeit height and width). Select标记几乎不可能自定义,并且在样式上(尽管高度和宽度)都受浏览器的左右。

You would be much better to construct and style your own using CSS if you are looking for a customisable option in which is cross-browser compatible. 如果您正在寻找跨浏览器兼容的可定制选项,那么使用CSS构造和设置自己的样式会更好。

I have used jQuery in order to complete this functionality. 我使用jQuery来完成此功能。 It also makes use of spans in order to replace the option tags, allowing for further styling (no external library needed, although there are many available): 它还使用跨度来替换option标签,从而可以进行进一步的样式设置(尽管有很多可用的库,但无需外部库):

 $('.item').hide(); $('.item').click(function () { var x = $(this).text(); $(this).siblings(".selected").text(x); $(this).slideUp().siblings(".item").slideUp(); }); $('.Drop').click(function () { $(this).parent().toggleClass("opened"); $(this).siblings(".item").slideToggle(); }); $('.selected').click(function () { $(this).parent().removeClass("opened"); $(this).siblings(".item").slideUp(); }); 
 div { height:30px; width:200px; background:lightgray; position:relative; } .item, .selected { display:block; height:30px; width:100%;position:relative; background:gray; transition:all 0.6s; line-height:30px; } .selected { background:none; display:block; } .item:hover { background:lightgray; } .Drop { position:absolute; top:0; right:0; height:100%; width:30px; background:tomato; transition:all 0.4s; transform:rotate(0deg); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <span class="selected">1</span> <span class="Drop"></span> <span class="item">1</span> <span class="item">2</span> <span class="item">3</span> <span class="item">4</span> <span class="item">5</span> <span class="item">6</span> </div> 

Note 注意

This is not a finished product, but is for demo only. 这不是成品,仅用于演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM