【jquery】基於 jquery 實現 ie 瀏覽器兼容 placeholder 效果

placeholder 是 html5 新增長的屬性,主要提供一種提示(hint),用於描述輸入域所期待的值。該提示會在輸入字段爲空時顯示,並會在字段得到焦點時消失。placeholder 屬性適用於如下類型的 input 標籤:text, search, url, telephone, email 以及 password。css

咱們先看下在谷歌瀏覽器中的效果,如圖所示:html

得到焦點時:html5

輸入字段:jquery

由於是 html5 屬性,天然低版本的瀏覽器好比 ie6-8 不兼容。下面就介紹下如何在低版本瀏覽器中顯示以上效果,話很少說直接上代碼。web

html:chrome

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="renderer" content="webkit"/>
    <meta name="keywords" content=""/>
    <meta name="description" content=""/>
    <title>基於 jquery 實現 ie 瀏覽器兼容 placeholder 效果</title>
    <style>
    *{margin:0;padding:0;}
    .txt{position:relative;font-size:12px;margin:10px;}
    .txt input{border:1px solid #ccc;height:30px;line-height:30px;padding:0 10px;width:200px;}
    .txt .txt-tip{color:#999;position:absolute;left:10px;top:0;height:32px;line-height:34px;}
    </style>
</head>
<body>
    <div class="txt">
        <input type="text" value=""/>
    </div>
</body>
</html>
<script src="js/jquery.min.js"></script>
<script src="js/placeholder.js"></script>
<script>
$(function(){
    var $input = $('.txt input');
    initPlaceholder($input, '請輸入內容', 'txt-tip');
});
</script>

placeholder.js:瀏覽器

function initPlaceholder($input, msg, classname){
    var isIE = !!window.ActiveXObject || 'ActiveXObject' in window;
    var isPlaceholder = 'placeholder' in document.createElement('input');
    if(isPlaceholder && !isIE){
        $input.attr('placeholder', msg);
    }else{
        var $tip = $('<span class="' + classname + '">' + msg + '</span>');
        $input.after($tip);
        $.data($input[0], 'tip', $tip);
        if($input.val() != ''){
            hidePHTip($input);
        }
        dealPHTip($input, $tip);
    }
}
function hidePHTip($input){
    var $tip = $.data($input[0], 'tip');
    if($tip){
        $tip.hide();
    }
}
function dealPHTip($input, $tip){
    var _deal = function(){
        var val = $input.val();
        if(val == ''){
            $tip.show();
        }else{
            $tip.hide();
        }
    };
    $tip.click(function(){
        $input.focus();
    });
    $input.on('input propertychange', function(){
        clearTimeout(timeout);
        var timeout = setTimeout(_deal, 0);
    });
}

實現原理:首先過濾下瀏覽器,非 ie 瀏覽器而且支持 placeholder 屬性就用 placeholder,ie 瀏覽器則用 span 代替 placeholder 文本內容,經過樣式定位在 input 上方,同時監聽 input 輸入框值的變化來判斷顯示或隱藏 span。ide

咱們來看下 ie6 瀏覽器中的效果:ui

得到焦點時:url

輸入字段:

能夠看到和谷歌瀏覽器的效果是一致的,惟一不足的就是文字沒有居中,能夠經過 css 進行修改。

相關文章
相關標籤/搜索