兼容ie7以上的 placeholder屬性


最近項目踩過的坑,不考慮ie的可以拐彎繞路走了。

css3的新屬性 占位符 placeholder用着多舒服 。

偏偏萬惡的ie不支持,網上有幾種方法是用焦點事件代替的,不過會失去原有的特性。一旦獲取焦點或者失去焦點占位符的文字就會消失。

而placeholder是在輸入文字時占位符的文字才會消失

強調一點,此方法只針對 input[type='text'],其他的不支持,比如passwrod

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="http://s28.9956.cn/static/v3_1/js/jquery.min.js"></script>
    </head>
    <body>
        <input type="" class="clo1" placeholder="電話">
        <script type="text/javascript">//'代碼保存成一個js文件引用即可。
            $(document).ready(function() {
                var doc = document,
                inputs = doc.getElementsByTagName('input'),
                supportPlaceholder = 'placeholder' in doc.createElement('input'),

                placeholder = function(input) {
                    var text = input.getAttribute('placeholder'),
                    defaultValue = input.defaultValue;
                    if (defaultValue == '') {
                        input.value = text
                    }
                    input.onfocus = function() {
                        if (input.value === text) {
                            this.value = ''
                        }
                    };
                    input.onblur = function() {
                        if (input.value === '') {
                            this.value = text
                        }
                    }
                };

                if (!supportPlaceholder) {
                    for (var i = 0,
                    len = inputs.length; i < len; i++) {
                        var input = inputs[i],
                        text = input.getAttribute('placeholder');
                        if (input.type === 'text' && text) {
                            placeholder(input)
                        }
                    }
                }
            });
        </script>
    </body>
</html>

再列舉一個支持passwrod的方法,比較猥瑣,用一個label標簽把input包起來,里面在加一個標簽代替placeholder的文字

先做個樣式,定位起來

<style type="text/css">
    label{position: relative;}
    label p{position: absolute;left: 5px;top:0px;margin: 0;padding: 0;}
</style>

 

<label>
    <input onfocus="$(this).siblings('p').hide();" onblur="if($(this).val()==''){$(this).siblings('p').show();}" type="password" class="psw">
    <p style="display: block;">請輸入密碼</p>
</label>

上面用的js方法寫的,寫到標簽里的,大家喜歡jquery的寫法的話,請看下面代碼

<script type="text/javascript">
    $(".psw").focus(function(){
        $("p").hide();
    });
    $(".psw").blur(function(){
        $("p").show();
    });
</script>

 


免責聲明!

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



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