跨浏览器的placeholder – 原生JS版

 

转自来源 : http://www.ifrans.cn/placehoder/javascript

 

跨浏览器的placeholder – 原生JS版

html5为input元素新增了一个属性”placeholder”,提供对输入字段预期值的提示信息,input为空且未得到焦点时显示,得到焦点时消失,很是实用。目前,大部分现代浏览器都对placeholder属性提供了支持,IE10也是支持的。若是须要使IE6~IE9等浏览器支持placeholder,只有借助js了。css

在这些不支持原生placeholder属性的浏览器下,一般使用value值来模拟,若是input为空且未得到焦点,就把value值设置为placeholder属性的值,一旦得到焦点,则将该input的值清空。这种方式在一些状况下会有问题,好比type=”password”的input的value值是以星号显示的,没法直接显示文字,除非同时更改type类型。再如,会给表单验证带来麻烦,若是某input是必填的,那么提交表单的时候该input的value为空或者为placeholder值时都不该该被提交,因此咱们要增长对value为placeholder的判断,或许这不是什么大问题,不过若是项目里使用了验证插件,而插件自己又不支持这种方式,仍是会带来些麻烦的。我在前不久的项目中就遇到了这个问题。如今重写了placeholder函数,在支持传统的使用value模拟placeholder方式的同时,提供了一种插入一个覆盖在input上的span标签来模拟placeholder的方式,可供必要时选择。先上demo:html

【点击这里查看 “跨浏览器的placeholder” DEMO】html5

下面是js代码主要部分,所有代码就不贴出了,能够查看demo页面的源码。稍后放出jquery插件版的。java

主要JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
  * @name placeHolder
  * @class 跨浏览器placeHolder,对于不支持原生placeHolder的浏览器,经过value或插入span元素两种方案模拟
  * @param {Object} obj 要应用placeHolder的表单元素对象
  * @param {Boolean} span 是否采用悬浮的span元素方式来模拟placeHolder,默认值false,默认使用value方式模拟
  */
function placeHolder(obj, span) {
     if (!obj.getAttribute( 'placeholder' )) return ;
     var imitateMode = span === true ? true : false ;
     var supportPlaceholder = 'placeholder' in document.createElement( 'input' );
     if (!supportPlaceholder) {
         var defaultValue = obj.getAttribute( 'placeholder' );
         if (!imitateMode) {
             obj.onfocus = function () { (obj.value == defaultValue) && (obj.value = '' );
                 obj.style.color = '' ;
             }
             obj.onblur = function () {
                 if (obj.value == defaultValue) {
                     obj.style.color = '' ;
                 } else if (obj.value == '' ) {
                     obj.value = defaultValue;
                     obj.style.color = '#ACA899' ;
                 }
             }
             obj.onblur();
         } else {
             var placeHolderCont = document.createTextNode(defaultValue);
             var oWrapper = document.createElement( 'span' );
             oWrapper.style.cssText = 'position:absolute; color:#ACA899; display:inline-block; overflow:hidden;' ;
             oWrapper.className = 'wrap-placeholder' ;
             oWrapper.style.fontFamily = getStyle(obj, 'fontFamily' );
             oWrapper.style.fontSize = getStyle(obj, 'fontSize' );
             oWrapper.style.marginLeft = parseInt(getStyle(obj, 'marginLeft' )) ? parseInt(getStyle(obj, 'marginLeft' )) + 3 + 'px' : 3 + 'px' ;
             oWrapper.style.marginTop = parseInt(getStyle(obj, 'marginTop' )) ? getStyle(obj, 'marginTop' ) : 1 + 'px' ;
             oWrapper.style.paddingLeft = getStyle(obj, 'paddingLeft' );
             oWrapper.style.width = obj.offsetWidth - parseInt(getStyle(obj, 'marginLeft' )) + 'px' ;
             oWrapper.style.height = obj.offsetHeight + 'px' ;
             oWrapper.style.lineHeight = obj.nodeName.toLowerCase() == 'textarea' ? '' : obj.offsetHeight + 'px' ;
             oWrapper.appendChild(placeHolderCont);
             obj.parentNode.insertBefore(oWrapper, obj);
             oWrapper.onclick = function () {
                 obj.focus();
             }
             //绑定input或onpropertychange事件
             if ( typeof (obj.oninput) == 'object' ) {
                 obj.addEventListener( "input" , changeHandler, false );
             } else {
                 obj.onpropertychange = changeHandler;
             }
             function changeHandler() {
                 oWrapper.style.display = obj.value != '' ? 'none' : 'inline-block' ;
             }
             /**
                  * @name getStyle
                  * @class 获取样式
                  * @param {Object} obj 要获取样式的对象
                  * @param {String} styleName 要获取的样式名
                  */
             function getStyle(obj, styleName) {
                 var oStyle = null ;
                 if (obj.currentStyle) oStyle = obj.currentStyle[styleName];
                 else if (window.getComputedStyle) oStyle = window.getComputedStyle(obj, null )[styleName];
                 return oStyle;
             }
         }
     }
}

 

-----------------------------------------------------------------------------------------------node

根据上面的东东, 简单的一个demo以下:jquery

<!DOCTYPE html>
<html>
<head>
    <meta charset="gb2312" />
    <title>跨浏览器placehoder</title>
    <meta name="author" content="ifrans.cn" />
    <meta name="description" content="跨浏览器的placehoder原生js版,让ie也支持placehoder" />
    <meta name="keywords" content="跨浏览器,placehoder,ie,原生js,表单" />
    <script type="text/javascript" src="./placeholder.js" ></script>

    <style>
        input{ vertical-align:middle; margin-left:10px; height:24px; line-height:24px; width:200px; padding-left:2px; }
        textarea{ vertical-align:middle; margin-left:10px; width:200px; height:50px; font:inherit; padding-left:2px;}
    </style>
</head>
<body onload="initPlaceholder('form1')">
<form id="form1">
    <h3>在不支持placeholder的浏览器下,经过插入悬浮的span元素方式模拟</h3>
    <p><label for="username1">用户名:</label><input type="text" name="username1" id="username1" placeholder="请输入用户名" value="" required></p>
    <p><label for="password1">密 码:</label><input type="password" name="password1" id="password1" placeholder="请输入密码" value="" required></p>
    <p><label for="address1">地 址:</label><input type="text" name="address1" id="address1" placeholder="请输入地址" value="" required></p>
    <p><label for="remarks1">备 注:</label><textarea placeholder="请输入备注" id="remarks1"></textarea></p>
</form>
 
</body>
</html>
/**
 * @name placeHolder
 * @class 跨浏览器placeHolder,对于不支持原生placeHolder的浏览器,经过value或插入span元素两种方案模拟
 * @param {Object} obj 要应用placeHolder的表单元素对象
 * @param {Boolean} span 是否采用悬浮的span元素方式来模拟placeHolder,默认值false,默认使用value方式模拟
 */
function placeHolder(obj, span) {
    if (!obj.getAttribute('placeholder')) return;
    var imitateMode = span===true?true:false;
    var supportPlaceholder = 'placeholder' in document.createElement('input');
    if (!supportPlaceholder) {
        var defaultValue = obj.getAttribute('placeholder');
        if (!imitateMode) {
            obj.onfocus = function () {
                (obj.value == defaultValue) && (obj.value = '');
                obj.style.color = '';
            }
            obj.onblur = function () {
                if (obj.value == defaultValue) {
                    obj.style.color = '';
                } else if (obj.value == '') {
                    obj.value = defaultValue;
                    obj.style.color = '#ACA899';
                }
            }
            obj.onblur();
        } else {
            var placeHolderCont = document.createTextNode(defaultValue);
            var oWrapper = document.createElement('span');
            oWrapper.style.cssText = 'position:absolute; color:#ACA899; display:inline-block; overflow:hidden;';
            oWrapper.className = 'wrap-placeholder';
            oWrapper.style.fontFamily = getStyle(obj, 'fontFamily');
            oWrapper.style.fontSize = getStyle(obj, 'fontSize');
            oWrapper.style.marginLeft = parseInt(getStyle(obj, 'marginLeft')) ? parseInt(getStyle(obj, 'marginLeft')) + 3 + 'px' : 3 + 'px';
            oWrapper.style.marginTop = parseInt(getStyle(obj, 'marginTop')) ? getStyle(obj, 'marginTop'): 1 + 'px';
            oWrapper.style.paddingLeft = getStyle(obj, 'paddingLeft');
            oWrapper.style.width = obj.offsetWidth - parseInt(getStyle(obj, 'marginLeft')) + 'px';
            oWrapper.style.height = obj.offsetHeight + 'px';
            oWrapper.style.lineHeight = obj.nodeName.toLowerCase()=='textarea'? '':obj.offsetHeight + 'px';
            oWrapper.appendChild(placeHolderCont);
            obj.parentNode.insertBefore(oWrapper, obj);
            oWrapper.onclick = function () {
                obj.focus();
            }
            //绑定input或onpropertychange事件
            if (typeof(obj.oninput)=='object') {
                obj.addEventListener("input", changeHandler, false);
            } else {
                obj.onpropertychange = changeHandler;
            }
            function changeHandler() {
                oWrapper.style.display = obj.value != '' ? 'none' : 'inline-block';
            }
            /**
             * @name getStyle
             * @class 获取样式
             * @param {Object} obj 要获取样式的对象
             * @param {String} styleName 要获取的样式名
             */
            function getStyle(obj, styleName) {
                var oStyle = null;
                if (obj.currentStyle)
                    oStyle = obj.currentStyle[styleName];
                else if (window.getComputedStyle)
                    oStyle = window.getComputedStyle(obj, null)[styleName];
                return oStyle;
            }
        }
    }
}

/**
 * 初始化, 对全部的input ,textarea应用. 在 body的onload中调用.
 */
function initPlaceholder(formid, doc) {
    if (!doc){ doc = document; }

    var oForm1 = doc.getElementById(formid);
    var oForm1Inputs = oForm1.getElementsByTagName('input');
    for(var i=0;i<oForm1Inputs.length;i++){
        placeHolder(oForm1Inputs[i],true);
    }
    var oForm1Textarea = oForm1.getElementsByTagName('textarea');
    for(var i=0;i<oForm1Textarea.length;i++){
        placeHolder(oForm1Textarea[i],true);
    }
}
相关文章
相关标签/搜索