當鼠標點擊文本框時js隱藏不要的內容js隱藏不要的內容,里面的默認文字隱藏,當鼠標離開文本框,里面的文字顯示
案例分析
2.如果獲得焦點,判斷表單里面是否為默認文字,如果是默認文字,就清空表單內容
3.如果失去焦點,判斷表單內容是否為空,如果為空,則表單內容改為默認文字
案例實現代碼
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
<style>
input {
color: #999;
}
style>
head>
<body>
<input type="text" value="請輸入內容!">
<script>
// 1.獲取元素
var text = document.querySelector('input');
// 2.注冊事件 獲得焦點事件 onfocus
text.onfocus = function() {
// console.log('得到了焦點');
if (this.value === '請輸入內容!') {
this.value = '';
}
// 獲得焦點需要把文本框里面的文字顏色變黑
this.style.color = '#333';
}
// 3. 注冊事件 失去焦點事件 onblur
text.onblur = function() {
// console.log('失去了焦點');
if (this.value === '') {
this.value = '請輸入內容!';
}
// 失去焦點需要把文本框里面的文字顏色變淺色
this.style.color = '#999';
}
script>
body>
html>
代碼運行結果