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


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

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

獲得焦點時:

輸入字段:

因為是 html5 屬性,自然低版本的瀏覽器比如 ie6-8 不兼容。下面就介紹下如何在低版本瀏覽器中顯示以上效果,話不多說直接上代碼。

html:

<!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。

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

獲得焦點時:

輸入字段:

可以看到和谷歌瀏覽器的效果是一致的,唯一不足的就是文字沒有居中,可以通過 css 進行修改。


免責聲明!

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



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