JavaScript實現(xiàn)顯示隱藏表單文字
本文實例為大家分享了JavaScript實現(xiàn)顯示隱藏表單文字的具體代碼,供大家參考,具體內(nèi)容如下
實現(xiàn)思路
運用 onfocus、onblur 事件
onfocus- - -獲取焦點(鼠標點擊輸入框,輸入框里面有閃動的光標)
onblur- - -失去焦點(鼠標不選中輸入框,輸入框里面失去閃動的光標)
1、給輸入框設置一個默認值
2、獲取輸入框?qū)ο?,給其綁定事件:onfocus 和 onblur
當獲取焦點時(onfocus)- - -判斷輸入框的value值是否是默認值,如果是默認值初始值,將value改為空,默認初始值就沒有了,可以輸入自己的
當時去焦點時(onblur)- - -判斷輸入框的value值是否沒有值,沒有的話,給value賦值默認值,未輸入內(nèi)容移開后又會顯示默認值了
3、還可以給獲取焦點和失去焦點兩種狀態(tài)的文字顏色設置不同,讓兩種狀態(tài)區(qū)分的更明顯
示例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="手機"> <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> <!--用戶名 顯示隱藏內(nèi)容 --> <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>
頁面效果:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
uniapp使用uni.chooseLocation()打開地圖選擇位置詳解
這篇文章主要給大家介紹了關于uniapp使用uni.chooseLocation()打開地圖選擇位置的相關資料,因為最近在項目中遇到一個要用戶授權位置且可以用戶自己選擇位置的功能,需要的朋友可以參考下2023-06-06JavaScript大數(shù)相加相乘的實現(xiàn)方法實例
這篇文章主要給大家介紹了關于JavaScript大數(shù)相加相乘的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10JavaScript修改、刪除數(shù)組中某個對象的某個屬性幾種方法
在JavaScript開發(fā)中,經(jīng)常需要修改數(shù)組中對象的屬性,下面這篇文章主要介紹了JavaScript修改、刪除數(shù)組中某個對象的某個屬性幾種方法,需要的朋友可以參考下2024-09-09javascript制作照片墻及制作過程中出現(xiàn)的問題
這篇文章主要介紹了javascript制作照片墻及制作過程中出現(xiàn)的問題,感興趣的朋友可以參考一下2016-04-04JavaScript實現(xiàn)Tab標簽頁切換的最簡便方式(4種)
這篇文章主要介紹了JavaScript實現(xiàn)Tab標簽頁切換的最簡便方式(4種),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06