IE不支持input標籤中html5的placeholder屬性,上網找了一下解決方法,感覺還不錯。
可以封裝成一個js文件,然後調用。
- $(function() {
- $("input").inputTip(); // 調用inputTip方法
- $("input[type='button']").focus(); // 頁面打開後焦點置於button上,也可置於別處。否則IE上刷新頁面後焦點在第一個輸入框內造成placeholder文字後緊跟光標現象
- });
- $.fn.extend({
- /**
- * 該方法爲了解決不支持placeholder屬性的瀏覽器下達到相似效果作用
- * @param _color 文本框輸入字體顏色,默認黑色
- * @param _plaColor 文本框placeholder字體顏色,默認灰色#a3a3a3
- */
- inputTip:function(_color, _plaColor) {
- _color = _color || "#000000";
- _plaColor = _plaColor || "#a3a3a3";
- function supportsInputPlaceholder() { // 判斷瀏覽器是否支持html5的placeholder屬性
- var input = document.createElement('input');
- return "placeholder" in input;
- }
- function showPassword(_bool, _passEle, _textEle) { // 密碼框和文本框的轉換
- if (_bool) {
- _passEle.show();
- _textEle.hide();
- } else {
- _passEle.hide();
- _textEle.show();
- }
- }
- if (!supportsInputPlaceholder()) {
- this.each(function() {
- var thisEle = $(this);
- var inputType = thisEle.attr("type")
- //alert(inputType);
- var isPasswordInput = inputType == "password";
- var isInputBox = inputType == "password" || inputType == "text";
- //alert("判斷是否爲密碼或文本====="+isInputBox);
- if (isInputBox) { //如果是密碼或文本輸入框
- var isUserEnter = false; // 是否爲用戶輸入內容,允許用戶的輸入和默認內容一樣
- var placeholder = thisEle.attr("placeholder");
- //alert("判斷是否爲密碼框======="+isPasswordInput);
- if (isPasswordInput) { // 如果是密碼輸入框
- //原理:由於input標籤的type屬性不可以動態更改,所以要構造一個文本input替換整個密碼input
- var textStr = "<input type='text' class='" + thisEle.attr("class") + "' style='" + (thisEle.attr("style") || "") + "' />";
- var textEle = $(textStr);
- textEle.css("color", _plaColor).val(placeholder).focus(
- function() {
- thisEle.focus();
- }).insertAfter(this);
- thisEle.hide();
- }
- thisEle.css("color", _plaColor).val("");//解決ie下刷新無法清空已輸入input數據問題
- if (thisEle.val() == "") {
- thisEle.val(placeholder);
- }
- thisEle.focus(function() {
- if (thisEle.val() == placeholder && !isUserEnter) {
- thisEle.css("color", _color).val("");
- //alert("focus===="+isPasswordInput);
- if (isPasswordInput) {
- showPassword(true, thisEle, textEle);
- }
- }
- });
- thisEle.blur(function() {
- if (thisEle.val() == "") {
- thisEle.css("color", _plaColor).val(placeholder);
- isUserEnter = false;
- //alert("blur===="+isPasswordInput);
- if (isPasswordInput) {
- showPassword(false, thisEle, textEle);
- }
- }
- });
- thisEle.keyup(function() {
- if (thisEle.val() != placeholder) {
- isUserEnter = true;
- }
- });
- }
- });
- }
- }
- });
下面是頁面的代碼,body部分:
- <div class="mt60 ml28" >
- <input type="text" class="txt" id = "username" placeholder="請輸入用戶名"/>
- </div>
- <div class="mt12 ml28">
- <input type="password" class="txt" id="password" placeholder="請輸入密碼"/>
- </div>
- <div class="mt12 ml28">
- <input type="text" class="ytxt vt mr5" id = "valicode" placeholder="請輸入驗證碼"/>
- </div>
結果表現爲: