转载:http://ourjs.com/detail/551b9b0529c8d81960000007
在这篇文章里,我将介绍如何不依赖JavaScript用纯css来改变下拉列表框的样式。
这篇文章是我转载的,有些朋友会碰到样式失效的问题,我就chrome和firefox的兼容问题解决如下:
注:这里select style里面的background:url () 的地址写上你自己的地址。
css样式里面要特别注意 background:transparent; -webkit-apperance:none; -moz-appearance:none;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#parent {
/*background: url('yourimage') no-repeat;*/
width: 120px;
height: 30px;
overflow: hidden;
background-color: #eeeeee;
}
#parent select {
border: none;
padding-left: 10px;
width: 120px;
height: 100%;
-webkit-appearance: none; /* Safari 和 Chrome */
-moz-appearance: none; /* Firefox */
background: transparent;
}
</style>
</head>
<body>
<div id="parent">
<select style="background: url(<?php echo URL::base().'modules/cool/media/images/down.png';?>) no-repeat 90% center;">
<option>what</option>
<option>the</option>
<option>hell</option>
</select>
</div>
</body>
</html>
效果如下:
![](https://img.haomeiwen.com/i2191251/4a3d31deff008179.png)
![](https://img.haomeiwen.com/i2191251/a92372d85f09669d.png)
![](https://img.haomeiwen.com/i2191251/6431f6b896ebda3a.png)
![](https://img.haomeiwen.com/i2191251/07ab8b91cac96b5b.png)
![](https://img.haomeiwen.com/i2191251/00e837cdbbc51f58.png)
一切看起来很好,很正常,直到你看到他/她设计的一个选择下拉框跟浏览器默认提供的样式有些不同!你说:“这没办法做!你应该不会抱怨设计师,其实更改下拉输入的默认样式并不是非常难的!Mobile 和现代浏览器的解决方案
下面是解决方案。
我们看到默认的下载选择框在firefox和chrome中是有些不同的
Chrome 和 Firefox 中分别是这样的:
![]()
![]()
其实用下列CSS就可以解决,原理是将浏览器默认的下拉框样式清除,然后应用上自己的,再附一张向右对齐小箭头的图片即可。
select {
/Chrome和Firefox里面的边框是不一样的,所以复写了一下/
border: solid 1px #000;/很关键:将默认的select选择框样式清除/
appearance:none;
-moz-appearance:none;
-webkit-appearance:none;/在选择框的最右侧中间显示小箭头图片/
background: url("http://ourjs.github.io/static/2015/arrow.png") no-repeat scroll right center transparent;/为下拉小箭头留出一点位置,避免被文字覆盖/
padding-right: 14px;
}
/清除ie的默认选择框样式清除,隐藏下拉箭头/
select::-ms-expand { display: none; }
在线示例 http://jsbin.com/yuxame/4/edit注*
这篇文章参考了 change-default-select-dropdown-style-just-css,但文中所述固定了select框的长度和高度,对此进行了修改。
更新: 针对旧版IE的解决方案
评论中提到 IE8/9并不支持 appearance:none CSS属性,想要支持的话可能需要非常特殊的方法,参考SF: 我们需要为其添加一个父容器,容器是用来覆盖小箭头的,然后为select添加一个向右的小偏移或者宽度大于父级元素。设置父级的CSS属性为超出部分不可见,即可覆盖即小箭头。然后再为父级容器添加背景图片即可。overflow: hidden并不能隐藏下拉框的显示。
HTML
<div id="parent">
<select>
<option>what</option>
<option>the</option>
<option>hell</option>
</select>
</div>
CSS
#parent {
background: url('yourimage') no-repeat;
width: 100px;
height: 30px;
overflow: hidden;
}
#parent select {
background: transparent;
border: none;
padding-left: 10px;
width: 120px;
height: 100%;
}
网友评论