純 JS 設置文本框的默認提示


HTML5 中有個新特性叫 placeholder,一般用它來描述輸入字段的預期值,適用於 text、search、password 等類型的 input 以及 textarea。示例如下:

<input type="text" placeholder="請輸入文本"><br>
<input type="search" placeholder="請輸入查詢關鍵字"><br>
<input type="password" placeholder="請輸入密碼"><br>
<textarea placeholder="請輸入描述"></textarea>

對用戶來說,placeholder 就是文本框中的輸入提示信息,往往是對預期值或預期格式的簡短描述。該提示在用戶輸入之前顯示在文本框中,在用戶開始輸入之后,該提示就會消失,此時文本框中顯示的是用戶輸入的內容。而如果文本框被置空,則該提示會再次顯示出來。

然而遺憾的是,早些年還有大量的 IE9 以及更低版本的 IE 用戶,這些瀏覽器都不支持 placeholder 屬性。所以那會兒做項目的時候,經常需要用 JS 來模擬 placeholder,以達到類似的效果。實現代碼如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>純 JS 設置文本框的默認值</title>
</head>
<body>
    <!-- 寫法一,設置默認值為 111 -->
    <input type="text" value="111" onfocus="if(this.value == '111'){this.value = ''}"
        onblur="if(this.value == ''){this.value = '111'}" />
    <br />
    <!-- 寫法二,設置默認值為 222,為了效果更逼真,將默認值設置為灰色 -->
    <input type="text" value="222" style="color: #cccccc"
        onfocus="if(this.value == '222'){this.value = ''; this.style.color = '#333333'}"
        onblur="if(this.value == ''){this.value = '222'; this.style.color = '#cccccc'}" />
    <br />
    <!-- 寫法三,設置默認值為 333,其實上面寫法中的 this 可以省略 -->
    <input type="text" value="333" style="color: #cccccc"
        onfocus="if(value == '333'){value = ''; style.color = '#333333'}"
        onblur="if(value == ''){value = '333'; style.color = '#cccccc'}" />
    <br />
    <!-- 寫法四,設置默認值為 444,將 html 中的 js 代碼提取出來 -->
    <input type="text" value="444" style="color: #cccccc" id="txt4" />
    <script>
        var txt4 = document.getElementById("txt4");
        txt4.onfocus = function () {
            if (this.value == '444') {
                this.value = '';
                this.style.color = '#333333';
            }
        }
        txt4.onblur = function () {
            if (this.value == '') {
                this.value = '444';
                this.style.color = '#cccccc';
            }
        }
    </script>
    <br />
    <!-- 寫法五,設置默認值為 555,換一種綁定事件的方式 -->
    <input type="text" value="555" style="color: #cccccc" id="txt5" />
    <script>
        var txt5 = document.getElementById("txt5");
        txt5.addEventListener("focus", function (){
            if (this.value == '555') {
                this.value = '';
                this.style.color = '#333333';
            }
        });
        txt5.addEventListener("blur", function () {
            if (this.value == '') {
                this.value = '555';
                this.style.color = '#cccccc';
            }
        });
    </script>
</body>
</html>

本文鏈接http://www.cnblogs.com/hanzongze/p/js-self-placeholder.html
版權聲明:本文為博客園博主 韓宗澤 原創,作者保留署名權!歡迎通過轉載、演繹或其它傳播方式來使用本文,但必須在明顯位置給出作者署名和本文鏈接!個人博客,能力有限,若有不當之處,敬請批評指正,謝謝!


免責聲明!

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



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