思路:首先需要知道表单的两个事件 (获得焦点 onfocus 失去焦点 onblur)
在注册事件的获得焦点中需要判断,表单里面的内容是否为默认文字,若是默认文字就清空表单(内容为空即可)。
在注册事件的失去焦点中需要判断,表单里面的内容是否为空,若是空就把表单内容改为默认内容即可。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
input {
color: #ccc;
}
</style>
</head>
<body>
<input type="text" value="手机" />
<script>
//获取元素
var ipt = document.querySelector("input");
//注册事件 获得焦点事件 onfocus
ipt.onfocus = function() {
if (this.value === "手机") {
this.value = "";
}
//获得焦点需把文本框里的颜色变黑
this.style.color = "#333";
};
//注册事件 失去焦点事件
ipt.onblur = function() {
if (this.value === "") {
this.value = "手机";
}
//失去焦点需把文本框的颜色变浅
this.style.color = "#ccc";
};
</script>
</body>
</html>