今天遇到一个这样的简单需求,整理如下:
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", "禁用状态,点击输入用户名");
this.setAttribute('class', 'form-control');
}
});
</script>
3.注意事项:
设置input的placeholder文字内容和颜色一定要分成两条语句执行,这样写是错误的,不能正常执行:
this.setAttribute("placeholder", "请输入用户名").setAttribute('class', 'form-control change'); //错误写法
感谢您的阅读^ - ^