• 认识input输入框的placeholder属性


    我们来认识下input输入框的placeholder属性。

    placeholder 属性提供可描述输入字段预期值的提示信息。(placeholder 属性适用于以下的 <input> 类型:text, search, url, telephone, email 以及 password)

    该提示会在输入字段为空时显示,并会在字段获得焦点时消失(IE10+获取焦点消失,Chrome,FF等在输入有值时消失)。

    IE10+,Chrome,Firefox,Safari支持placeholder属性(IE6/7/8/9不支持)。 

    在页面显示类似:

    html代码:

    为了让IE6/7/8/9支持placeholder属性,我说说自己解决方法。

    首先判断浏览器是否支持placeholder属性。

    var isSupport = function(){
    	return 'placeholder' in document.createElement('input');
    }
    

      如果不支持,其中分两种情况:

      如果是密码框(type="password"),就创建一个类似的input标签并且设置(type="text"),把原来有placeholder属性的input标签隐藏,并且把placeholder的值赋给新建的input标签,最后把新建的input标签插入到原来的input标签后面。

    if(input.type == 'password'){
    	var newInput = document.createElement('input');
    	newInput.type = 'text';
    	newInput.value = input.placeholder;
    	input.style.display = none;
    	input.parentNode.insertBefore(newInput,input.nextSibling);
    }
    

      如果是一般文本框(type="text")或者其他类型 search, url, telephone, email,就设置input的值等于placeholder属性的值。

    if(input.type == 'text'){
    	input.value = input.placeholder;
    }
    

    然后是获得焦点时:

      密码框类型是新建input标签获得焦点,隐藏新建input标签,显示原来的密码框。

    newInput.onfocus = function(){
    	newInput.style.display = 'none';
    	input.style.display = '';
    	input.focus();
    }
    

      其他类型获得焦点,清空设置的value值。

    input.onfocus = function(){
    	if(input.value == input.placeholder) input.value = '';
    }

    最后是失去焦点时:

      密码框类型是判断原有的input失去焦点,如果有用户输入的值,不做任何改变,如果没有就隐藏,然后显示新建的input标签。

    input.onblur = function(){
    	if(input.value == ''){  
    		newInput.style.display = '';  
    		input.style.display = 'none'; 
    	}
    }
    

      其他类型失去焦点判断用户是否有输入的值,如果没有,就设置value值为placeholder的值,如果有就不做任何改变。

    input.onblur = function(){
    	if(input.value == '') input.value = input.placeholder;
    }
    

    总的来说分两块处理,密码类型和非密码类型。

    为了方便,兼容各大浏览器,一般要封装成一个插件,下面是我的一个封装,供参考。

    /**
     * LBS PlaceHolder
     * ============================================
     * 直接调用:
     * PlaceHolder.init() //页面所有input
     * PlaceHolder.create(input) //单个或多个input
     * ============================================
     * PlaceHolder.className 
     * 为显示占位文本input添加类名  默认placeholder
     * ============================================
    **/
    
    ;(function(){
    	var PlaceHolder = {
    	    _support: (function(){
    	        return 'placeholder' in document.createElement('input');
    	    })(),
    	    className: 'placeholder',
    	    init: function(){
    	        if(!PlaceHolder._support){
    	            var inputs = document.getElementsByTagName('input');
    	            PlaceHolder.create(inputs);
    	        }
    	    },
    	    create: function(inputs){
    	    	if(PlaceHolder._support) return;
    	        var input = null, i = 0, n = inputs.length, holds = [];
    	        if(!n) inputs = [inputs];
    	        for(; i < n; i++) holds[i] = inputs[i];
    	        for(i = 0; i < n; i++){
    	            input = holds[i];
    	            if(PlaceHolder.attr(input,'placeholder') !== '' && PlaceHolder.attr(input,'placeholder') !== null){
    		           if(input.type == 'password'){
    		           		var newInput = document.createElement('input');
    						newInput.type = 'text';
    						newInput.className = input.className + ' ' + PlaceHolder.className;
    						newInput.value = PlaceHolder.attr(input,'placeholder');
    						PlaceHolder.after(newInput,input);
    						input.style.display = 'none';
    						PlaceHolder._newInputBind(input,newInput);
    		           }else{
    		           		PlaceHolder._setValue(input);
    						PlaceHolder._inputBind(input);
    		           }
    	            }
    	        }
    	    },
    		_newInputBind: function(input,newInput){
    			PlaceHolder.on(newInput,'focus', function(){
    				newInput.style.display = 'none';
    				input.style.display = ''; 
    				input.focus();
    			});
    			PlaceHolder.on(input,'focus', function(){
    				newInput.style.display = 'none';
    				input.style.display = '';
    				input.select();
    			});
    			PlaceHolder.on(input,'blur', function(){
    				if(input.value === ''){  
    					newInput.style.display = '';  
    					input.style.display = 'none'; 
    				} 
    			});
    		},
    		_inputBind: function(input){
    			PlaceHolder.on(input,'focus',function(){
    				if(input.value === PlaceHolder.attr(input,'placeholder')){
    					input.value = '';
    					PlaceHolder.removeClass(input,PlaceHolder.className);
    					input.select();
    				}
    			});
    			PlaceHolder.on(input,'blur',function(){
    				if(input.value === '') PlaceHolder._setValue(input);
    			});
    		},
    	    _setValue: function(input){
    	        input.value = PlaceHolder.attr(input,'placeholder');
    			PlaceHolder.addClass(input,PlaceHolder.className);
    	    },
    		on: function(el,type,fn){
    		  if(el.addEventListener) el.addEventListener(type, fn, false);
    		  else el.attachEvent('on' + type, function(){return fn.call(el,event)});
    		},	
    		hasClass: function (o,c){
    			return -1 < (' '+ o.className +' ').indexOf(' '+ c +' ');
    		},
    		addClass: function(o,c){
    			if(!PlaceHolder.hasClass(o,c)) o.className += ' '+ c;
    		},
    		removeClass: function(o,c){
    			if(PlaceHolder.hasClass(o,c)){ 
    				var reg = new RegExp('(\s|^)'+ c +'(\s|$)'); 
    				o.className = o.className.replace(reg,'');
    			}
    		},
    		attr: function(o,v){
    			return o.v || o.getAttribute(v);
    		},
    		after: function(n,o){
    			var parent = o.parentNode;
    			parent.lastChild == o ? parent.appendChild(n) : parent.insertBefore(n,o.nextSibling);
    		}
    	};
    	window.PlaceHolder === undefined && (window.PlaceHolder = PlaceHolder);
    }());
    

     有两种用法:

    1. 页面所有input标签

    PlaceHolder.init();
    

    2.单个或者多个的input标签

    var input = document.getElementById('username_input');
    PlaceHolder.create(input);
    var inputs = document.getElementsByTagName('input');
    PlaceHolder.create(inputs);
    

    其中有个 PlaceHolder.className , 这是个类名引用,默认类名称是 placeholder 

    为什么要加这个类名呢?主要是为了设置placeholder占位文本在input标签中的颜色。

    为了得到一致的占位文本颜色,需要设置样式(假设为红色)

    /*输入时的颜色*/
    input{color: #000;}
    /*占位时的颜色*/
    input.placeholder{color: #f00;}/* IE6/7/8/9 */
    input::-webkit-input-placeholder{ color:#f00;}/* WebKit */
    input:-moz-placeholder{color:#f00;}/* Firefox 4 - 18 */
    input::-moz-placeholder{color:#f00;}/* Firefox 19+ */
    input:-ms-input-placeholder{color:#f00;}/* IE10+ */
    

    有时候会发现设置的颜色没有起作用,注意下CSS样式的优先级。

    可以在各个浏览器看看效果:

    到这里,差不多解决了各个浏览器placeholder问题,其实仔细点会发现一些差别。

    支持placeholder的(IE10+获取焦点消失,Chrome,FF等在输入有值时消失)

    插件是获取焦点消失,为了某些人要所有浏览器一致的要求,得做出一些改变,原理也差不多。

    世界本来是丰富多彩的,不同的浏览器不同的体验有什么不好呢?

  • 相关阅读:
    JS_Boolean Logic
    js String
    .Net之路(二)简介
    自考 操作系统概论计算机系统
    IT大学生最重要的五个能力
    数据库表及字段命名规范
    简述MVC分层
    .Net之路(一)概述
    设计模式(4)迭代器模式
    .Net之路(三)如何连接数据库?
  • 原文地址:https://www.cnblogs.com/eyeear/p/4584965.html
Copyright © 2020-2023  润新知