利用原生js修改input的placeholder的默认字体颜色

    昨晚有朋友求助,碰到一个需求,需要修改input,第一个需求是鼠标点击input,提示字不消失,但是原input里面写的是value = "提示字样",我让他将value改为placeholder之后解决了鼠标点击输入框提示字消失的问题;他们第二个需求是:鼠标点击提示字不消失并且该字体需要变颜色,最可气他们工程师还将js写进了input标签里(个人在这里十分不赞同这种做法,不利于维护,而且看起来很乱)。

  

1 <!doctype html>
2 <html lang="en">
3  <head>
4   <title>原代码</title>
5  </head>
6  <body>
7         <input type="text" class="form-control" id="inputEmail3" name="textfield" value="联系人" onfocus="if (value =='联系人'){value =''}" onblur="if (value ==''){this.value ='联系人';this.style.color='#000';}" />
8  </body>
9 </html>

 

  由于之前没有碰到过这种需求,所以查阅了资料,做了如下的更改:

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>修改后的代码</title>
  <style type="text/css">
            #inputEmail3.change::-webkit-input-placeholder {
                    color: red;
            }
            #inputEmail3.change::-moz-placeholder {
                    color: red;
            }
       #inputEmail3.change::-ms-input-placeholder {
                    color: red;
            }
</style> </head> <body> <input type="text" class="form-control" id="inputEmail3" name="textfield" placeholder="联系人" onfocus="this.setAttribute('class', 'form-control change')" onblur="this.setAttribute('class', 'form-control')"/> </body> </html>

注:IE不支持placeholder属性,故如需要在IE上兼容,需要先解决兼容问题。这里有一些其他作者方法仅供参考:http://www.cnblogs.com/yjzhu/p/4398835.html

最后。建议大家如果碰到这种需求还是将js,css,html放在各自的文件里,这样有助于内容,样式,功能的分离,有助于网站维护。

posted @ 2016-11-16 14:06  Sihan  阅读(13429)  评论(0编辑  收藏  举报