一個友好的文本框內顯示提示語 jquery 插件


插件實現文本框內默認顯示提示語,當文本框獲得焦點時提示語消失。 如果沒有輸入或輸入為空則失去焦點時提示語再次出現。
同時它的使用非常舒適簡單,引入插件及 jquery 后,在原有的文本框內加上樣式類(class="prompt-input")以及設置值(value="Your prompt")為提示語就可以了。

像這樣:

1 <input class="prompt-input" type="text" value='Your prompt' />

同時獲取值的方式無需任何更改,這樣在已完成的項目上加上插件效果也沒有任何改動上的壓力了。

實現 js:

 1 /*
 2  *
 3  * Version: 1.2.0
 4  * Author: jinglan.woo(a)gmail.com
 5  * Date: 2014.08.07
 6  *
 7  * Friendly prompt text input box: 
 8  * the text input box has focus prompt disappears 
 9  * and  prompt appears again when it out of focus
10  *
11  */
12 
13 (function ($) {
14     $.fn.promptInput = function (prompt, fontColor) { 
15         var $this = $(this); //當前傳入文本框
16         prompt = prompt ? prompt : $this.val(); //在輸入框中顯示的提示語
17         fontColor = fontColor ? fontColor : '#ccc'; //提示語的顏色
18 
19         var $promptInput = $this.clone(); //克隆傳入的文本框,用於展示
20 
21         $promptInput.addClass('prompt-input').css('color', fontColor)
22             .attr('prompt', prompt).attr('type','text').removeAttr('name').removeAttr('id')
23             .val(prompt); //實例化用於展示的文本框
24 
25         $promptInput
26             .focusin(function () { //獲取焦點時去掉提示
27                 $(this).css('color', '');
28                 if ($(this).val() == $(this).attr('prompt')) {
29                     $(this).val('');
30                 }
31             })
32             .focusout(function () { //失去焦點時顯示提示
33                 if ($(this).val().replace(/\s/g, '') == '') {
34                     $(this).val($(this).attr('prompt')).css('color', fontColor);
35                     $(this).next().val('');
36                 }
37             }).change(function () { //值發生改變時,同時為當前傳入文本框賦值
38                 $(this).next().val($(this).val());
39             }); 
40 
41         $this.attr('type', 'hidden').val(''); //改變當前傳入文本框類型為隱藏域
42         $promptInput.insertBefore($this); //同時追加克隆體到頁面
43     };
44 })(jQuery);
45 
46 $(function () {
47     $('.prompt-input').each(function (index, element) { //頁面加載完成自動檢測 .prompt-input 類,加載效果
48         $(element).promptInput();
49     });
50 });
jquery.promptInput.js

使用 html:

 1 <!DOCTYPE html>
 2 <head>
 3     <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
 4     <script src="jquery.promptInput.js"></script>
 5     <script type="text/javascript">
 6         $(function () {
 7             $('#signUp').click(function () {
 8                 alert('username: ' + $('#username').val());
 9             });
10         });
11     </script>
12 </head>
13 <body>
14         <input class="prompt-input" type="text" value="請輸入用戶名" id="username" />
15         <div id="signUp">Sign up</div>
16 </body>
17 </html>

 可以復制以上代碼直接運行,也可以在這里下載完整代碼及演示。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM