1. 程式人生 > >在IE9中實現placeholder功能

在IE9中實現placeholder功能

                     

placeholder是文字框用來提示內容的屬性,比如:

<input id="txt" type="text" name="account" placeholder="請輸入帳號">
  • 1

會顯示為:
這裡寫圖片描述
然而IE9不支援此屬性,可以使用js來簡單模擬placeholder行為。

我的基本思路是為輸入框設定value值,並設定字型顏色,根據輸入框內容模擬placeholder。

對於密碼輸入框placeholder屬性的實現,我的思路是新增一個普通的文字輸入框在密碼框的位置,當點選輸入框的時候隱藏它,顯示原本的密碼輸入框並設定焦點。

<!DOCTYPE html><html lang
="en">
<head>    <meta charset="UTF-8">    <title></title>    <script src="../jquery.js"></script>    <style>        input{            width:170px;            height:15px;            vertical-align: middle;        }        .hint{            color:#666;        }
        .hide{            display: none;        }   
</style></head><body>    <form action="" method="get">        文字框:<input id="txt" type="text" name="account" placeholder="請輸入帳號">        <hr>        密碼框:        <span>            <input id="pwd" type="password"
name="password" placeholder="請輸入密碼">
<input id="pwdSpan" type="text" placeholder="請輸入密碼">        </span>        <button type="submit" onclick="submit()">Submit</button>    </form>    <script>        $(function(){            $("#pwdSpan").hide();        })    </script>    <!--[if lte IE 9]>        <script src="ie.js"></script>    <![endif]--></body></html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

ie.js:

$(function(){    var txtHolder=$("#txt").attr("placeholder");    var pwdHolder=$("#pwdSpan").attr("placeholder");    $("#txt").val(txtHolder).addClass("hint");    $("#pwdSpan").val(pwdHolder).addClass("hint").show();    $("#pwd").hide();    $("#txt").focus(function(){        if($(this).val() == txtHolder){            $(this).val("").removeClass("hint");        }    }).blur(function(){        if($(this).val().trim() === ""){            $(this).val(txtHolder).addClass("hint");        }    });    $("#pwdSpan").focus(function(){        $(this).css("display", "none");        $("#pwd").show().focus();    })    $("#pwd").blur(function(){        if($("#pwd").val().trim() == ""){            $(this).hide();            $("#pwdSpan").show();        }    })})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

由於Chrome等瀏覽器本身是支援placeholder屬性的,所以需要判斷瀏覽器型別再載入js檔案。

IE中文字輸入框和密碼輸入框預設大小略有不同,需要一起定義一下;

而且兩個輸入框不能顯示在橫向保持對齊。只要新增vertical-align: middle; 就可以了。

初始狀態:

這裡寫圖片描述

輸入一些內容後:

這裡寫圖片描述

當然這個只停留在了實現,如果能以外掛什麼的形式展示的話,功能性會更強。