JavaScript實現顯示隱藏表單文字
阿新 • • 發佈:2021-09-29
本文例項為大家分享了實現顯示隱藏表單文字的具體程式碼,供大家參考,具體內容如下
實現思路
運用 onfocus、onblur 事件
onfocus- - -獲取焦點(滑鼠點選輸入框,輸入框裡面有閃動的游標)
onblur- - -失去焦點(滑鼠不選中輸入框,輸入框裡面失去閃動的游標)
1、給輸入框設定一個預設值
2、獲取輸入框物件,給其繫結事件:onfocus 和 onblur
當獲取焦點時(onfocuwww.cppcns.coms)- - -判斷輸入框的value值是否是預設值,如果是預設值初始值,將value改為空,預設初始值就沒有了,可以輸入自己的
當時去焦點時(onblur)- - -判斷輸入框的value值是否沒有值,沒有的話,給value賦值預設值,未輸入內容移開後又會顯示預設值了
3、還可以給獲取焦點和失去焦點兩種狀態的文字顏色設定不同,讓兩種狀態區分的更明顯
示www.cppcns.com例1:
程式碼:
<!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>獲取/失去焦點</title> <style> input { color: #ccc; outline: none; } </style> </head> <body> <input type="text" value="手機"www.cppcns.com> <script> var text = document.querySelector('input'); text.onfocus = function() { if (this.value === '手機') { this.value = ''; } this.style.color = '#333'; } text.onblur = function() { if (this.value === '') { this.value = '手機'; } this.style.color = '#ccc'; } </script> </body> </html>
頁面效果:
示例2
程式碼:
<!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>使用者名稱 顯示 隱藏</title> <style> input { font-size: 14px; color: #999; outline: none; padding: 3px 0 3px 10px; border: 1px solid #ccc; } </style> </head> <body> <!--使用者名稱 顯示隱藏內容 --> <input type="text" value="郵箱/ID/手機號" class="userName"> <script> var userName = document.querySelector('.userName'); userName.onfocus = function() { if (this.value === '郵箱/ID/手機號') { this.value = ''; this.style.borderColor = 'pink'; } else { this.style.borderColor = 'pink'; this.style.color = '#999'; } } userName.onblur = function() { if (this.value === '') { this.value = '郵箱/ID/手機號'; this.style.borderColor = '#ccc'; this.style.color = '#999'; } else { this.style.borderColor = '#ccc'; this.style.color = '#333'; } } </script> </body> </html>
頁面效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。