CSS修改placeholder样式的方法介绍(代码示例)

2020-07-23 15:17:00
本篇文章给大家带来的内容是CSS修改placeholder样式的方法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。

项目用经常遇到修改input的placeholder的颜色的需求,这里来看一下placeholder如何用css设置:

首先来看一下chrome默认的input样式

<input type="text" placeholder="hello world">

(placeholder)

1.png

(input style)

2.png

可以发现,placeholderinput的默认颜色是有点区别的。现在我们来修改input 的颜色

<input type="text" placeholder="hello world" style="color: red">

(placeholder)

3.png

(input)

4.png

不难发现color属性只能改变输入值的颜色,placeholder的颜色没人任何变化。so,如何来改变placeholder的颜色。

要改变placeholder的颜色就要使用到伪类::placeholder

<style>    input::placeholder {        color: green;    }</style><input type="text" placeholder="hello world" style="color: red;">

(placeholder)

5.png

(input)

6.png

需要注意的是::palceholder伪类的兼容性,以上是在chrome浏览器的运行结果,同样的代码在IE11中就成了这样

(placeholder - ie11)

7.png

(input - ie11)

8.png

IE解决方案:

首先IE9及以下不支持placeholder。IE10需要用:-ms-input-placeholder,并且属性需要加上!important提高优先级。

<style>    input:-ms-input-placeholder {        color: green !important;    }</style><input type="text" placeholder="hello world" style="color: red;">

(placeholder ie11)

9.png

(input ie11)

10.png

之后给出其他浏览器的适配方案

/* - Chrome ≤56,   - Safari 5-10.0   - iOS Safari 4.2-10.2   - Opera 15-43   - Opera Mobile >12   - Android Browser 2.1-4.4.4   - Samsung Internet   - UC Browser for Android   - QQ Browser */::-webkit-input-placeholder {    color: #ccc;    font-weight: 400;}/* Firefox 4-18 */:-moz-placeholder {    color: #ccc;    font-weight: 400;}/* Firefox 19-50 */::-moz-placeholder {    color: #ccc;    font-weight: 400;}/* - Internet Explorer 10–11   - Internet Explorer Mobile 10-11 */:-ms-input-placeholder {    color: #ccc !important;    font-weight: 400 !important;}/* Edge (also supports ::-webkit-input-placeholder) */::-ms-input-placeholder {    color: #ccc;    font-weight: 400;}/* CSS Working Draft */::placeholder {    color: #ccc;    font-weight: 400;}

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。