/** * @name placeholder * @class 跨浏览器placeholder,对于不支持原生placeholder的浏览器,通过value或插入span元素两种方案模拟 * @param {object} obj 要应用placeholder的表单元素对象 * @param {boolean} span 是否采用悬浮的span元素方式来模拟placeholder,默认值false,默认使用value方式模拟 */ function placeholder(obj, span) { if("string" == typeof(obj)){obj=document.getelementbyid(obj);if(obj == null){return;}} 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; } } } }