小編給大家分享一下javascript如何實現輸入框內容提示及隱藏功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
有時輸入框較小,希望輸入內容后,出現一個有放大輸入內容的提示框
實現思路
頁面上先編寫出提示框,然后將提示框的css屬性:display設置成none,隱藏起來
獲取輸入框元素對象、信息提示框元素對象
為輸入框元素對象綁定鍵盤事件- - -keyup,
事件處理程序:判斷輸入的內容是否為空,不為空- - -將輸入框的內容賦值給信息提示框,并設置信息提示框顯示:display設置成block;為空,設置提示框不顯示
添加獲取焦點和失去焦點事件。
blur- - -失去焦點:鼠標不選中輸入框,輸入框中無光標閃爍時,設置信息提示框不顯示:display設置成none
focus- - -獲取焦點:鼠標點擊輸入框,輸入框中有光標閃爍時,判斷一下,如果輸入框有內容,信息提示框顯示;
注意這里是鍵盤松開事件,不要用鍵盤按下事件:keydown或keypress,按下時還沒有將打的字錄入,鍵盤松開時,才會錄入打的字
代碼示例:
<!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> * { margin: 0; padding: 0; } input { outline-style: none; } .search { position: relative; width: 220px; margin: 100px auto; } .info { display: none; position: absolute; top: -40px; left: 0; width: 170px; padding: 5px 0; font-size: 18px; line-height: 20px; border: 1px solid rgba(0, 0, 0, .2); box-shadow: 0px 2px 4px rgba(0, 0, 0, .2); } .info::before { content: ''; width: 0; height: 0; position: absolute; top: 28px; left: 18px; border: 8px solid #000; border-color: #fff transparent transparent; border-style: solid dashed dashed; } </style> </head> <body> <div class="search"> <div class="info">(*´▽`)ノノ</div> <input type="text" class="express" placeholder="請輸入要查詢的快遞單號"> <input type="button" value="查詢"> </div> <script> var expressNo = document.querySelector('.express'); var info = document.querySelector('.info'); expressNo.addEventListener('keyup', function() { console.log(expressNo.value); console.log(info.innerHTML); if (this.value == '') { info.style.display = 'none'; } else { info.style.display = 'block'; info.innerHTML = this.value; } }); // 失去焦點,隱藏盒子 expressNo.addEventListener('blur', function() { info.style.display = 'none'; }) //獲得焦點事件,顯示盒子 expressNo.addEventListener('focus', function() { if (this.value !== '') { info.style.display = 'block'; } }) </script> </body> </html>
頁面效果:
以上是“javascript如何實現輸入框內容提示及隱藏功能”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。