10 09/2014

跨浏览器 Placeholder

最后更新: Wed Sep 10 2014 12:37:50 GMT+0800
<script>
var doc = document,
    inputs = doc.getElementsByTagName('input'),
    supportPlaceholder = 'placeholder' in doc.createElement('input'),
    placeholder = function(input){
        var text = input.getAttribute('placeholder'),
            defaultValue = input.defaultValue;

        input.value = text;
        input.onfocus = function(){
            if(input.value === defaultValue || 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>

学习笔记:

  • 连续 var
  • 检测浏览器支持 supportPlaceholder = ‘placeholder’ in doc.createElement(‘input’)

via 跨浏览器 HTML5 Placeholder

但是如果有 默认值的话,似乎有 bug。一旦获得焦点,defaultValue 就被强制换成 placeholder 了,改了一个版本(为了方便chrome调试,placeholder -> placeholder2 了;用的时候改回来)

<input placeholder2="123" value="88888" />

<script>
var doc = document,
    inputs = doc.getElementsByTagName('input'),
    supportPlaceholder = 'placeholder2' in doc.createElement('input'),
    placeholder = function(input){
        var text = input.getAttribute('placeholder2'),
            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('placeholder2');
        if(input.type === 'text' && text){
            placeholder(input);
        }
    }
}
</script>