获得焦点: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>
input {
width: 200px;
height: 20px;
color: #ccc;
}
</style>
</head>
<body>
<input type="text" value="电脑">
<script>
var text = document.querySelector('input');
text.onfocus = function() {
if (text.value == '电脑') {
this.value = '';
}
this.style.color = '#333';
}
text.onblur = function() {
if (text.value == '') {
this.value = '电脑';
}
this.style.color = '#ccc';
}
</script>
</body>
</html>