JS动态修改某个input标签的placeholder中的⽂字内容和颜⾊今天遇到⼀个这样的简单需求,整理如下:
1. 刚加载页⾯的时候,给⼀个input标签默认灰⾊的placeholder提⽰:
2. ⽤户点击输⼊框的时候,更改placeholder⽂字内容,并且颜⾊改为红⾊:
3. 当输⼊框失去焦点时,如果没有输⼊任何⽂字,恢复原本的灰⾊提⽰状态
下⾯简单介绍⼀下我的写法,仅供参考,如有错误,欢迎留⾔批评指正:
1. ⾸先html内容如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS动态修改input的placeholder⽂字内容和颜⾊</title>
<style type="text/css">
/*默认的placeholder⽂字颜⾊*/
::-webkit-input-placeholder {
color: #808080;
}
/*需要变化的placeholder⽂字颜⾊*/
#myInput.change::-webkit-input-placeholder {
color: red;
}
</style>
</head>
<body>
⽤户名:<input id="myInput" name="textfield" type="text" class="form-control" placeholder="禁⽤状态,点击输⼊⽤户名" /> </body>
</html>
2.引⼊jquery⽂件(路径对照⾃⼰的修改),写JS代码:
<script type="text/javascript" src="d:\......\jquery-1.11.3.js"></script>
<script type="text/javascript">
$("#myInput").focus(function () {
this.setAttribute("placeholder", "请输⼊⽤户名");
this.setAttribute('class', 'form-control change');
}).blur(function () {
if (!$("#myInput").val()) {
//输⼊框没有输⼊任何值的情况下,恢复默认状态
this.setAttribute("placeholder", "禁⽤状态,点击输⼊⽤户名");
html radio点击变颜this.setAttribute('class', 'form-control');
}
});
</script>
3.注意事项:
设置input的placeholder⽂字内容和颜⾊⼀定要分成两条语句执⾏,这样写是错误的,不能正常执⾏:
this.setAttribute("placeholder", "请输⼊⽤户名").setAttribute('class', 'form-control change'); //错误写法感谢您的阅读^ - ^