码迷,mamicode.com
首页 > Web开发 > 详细

跨浏览器的placeholder – 原生JS版

时间:2014-09-03 14:48:16      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   使用   java   

 

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

 

跨浏览器的placeholder – 原生JS版

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

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

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

下面是js代码主要部分,全部代码就不贴出了,可以查看demo页面的源码。稍后放出jquery插件版的。

主要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;
            }
        }
    }
}

 

-----------------------------------------------------------------------------------------------

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

<!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);
    }
}

 

 

跨浏览器的placeholder – 原生JS版

标签:des   style   blog   http   color   os   io   使用   java   

原文地址:http://www.cnblogs.com/yangw/p/3953613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!