DIV CSS 佈局教程網

JS實作輸入框與清空按鈕聯動效果
編輯:關於JavaScript     

在現代表單互動中,「有內容時才顯示清空按鈕」是一個常見且貼心的設計。本文直接分享關鍵程式碼,透過簡單的函式判斷輸入框的值,來控制清空按鈕的顯示與隱藏,並在點擊時一鍵清空內容。

關鍵程式碼如下:

 <!DOCTYPE html><html><head><meta charset="UTF-8"><title>輸入框清空按鈕</title><script src="js/jquery1.8.3.min.js"></script><script> /** * 校驗當前輸入框的值,如果不為空顯示清空按鈕 * @param element */ function checkInput(element){ var value = $(element).val(); if(value!=null&&''!=value) $(element).parent().parent().children().children('.button').removeClass('none'); else $(element).parent().parent().children().children('.button').addClass('none'); } /** * 清空輸入框內容 * @param element */ function clearInput(element){ $(element).parent().parent().children().children('input').val(''); $(element).addClass('none'); } </script><style>.none{ display: none; }.height-20{ height:20px;}.button{ color: red; font-size:18px; width:100px; height:18px;border:1px solid red; border-radius:5px; }</style></head><body><div><div><input type="text" placeholder="輸入試試看" onkeyup="checkInput(this);" > </div><div class="height-20" ></div><div> <a class="none button" onclick="clearInput(this);" >clear input</a></div></div></body> </html>

運作邏輯說明

整體思路相當直觀:checkInput 函式在每次按鍵(onkeyup)時取得輸入框的值,若內容不為空則移除按鈕的 none 樣式讓它顯示;反之則加上 none 使其隱藏。clearInput 函式則負責把輸入框的值清空,並同時把按鈕藏起來。

以上就是本次分享的輸入框與清空按鈕聯動效果,希望對大家的開發有所幫助。若有任何疑問,歡迎留言討論。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved