让IE支持placeholder属性,跨浏览器placehoder

在html5中,文本框,也就是input, type为text,或者password,新增了一个属性placeholder,也就是占位符,以下是firefox浏览器下的表现形式,当输入的时候,占位符就会消失。这个属性非常好用,因为有这个必要html5才会因素这个属性,然而在IE下,就没有这效果,以下是IE9的表现。

下面是JS版:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>跨浏览器placehoder</title>
<meta name="author" content="ifrans.cn" />
<meta name="description" content="跨浏览器的placehoder原生js版,让ie也支持placehoder" />
<meta name="keywords" content="跨浏览器,placehoder,ie,原生js,表单" />
<style>
body{font:12px/1.5 Arial,"\5b8b\4f53", sans-serif;-webkit-text-size-adjust:100%;color:#333333;background:white;}
h1,h2,h3,h4,h5,h6,button,input,select,textarea{font-size:100%; font-weight:normal; font-style:normal;}
table{border-collapse:collapse;border-spacing:0;font-size:100%;font:inherit;empty-cells:show}
fieldset,img{border:0;}
address,caption,cite,code,dfn,th,var{font-style:normal; font-weight:normal;}
button,input,select,textarea{font-family:Arial, Helvetica, sans-serif;text-decoration: none;outline:none;-moz-outline:none;font-size:100%;}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{vertical-align:middle;-webkit-appearance:button;cursor:pointer;}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none;}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}
textarea{resize:none;overflow:auto;vertical-align:top}
ul,ol,li,dl{list-style-type:none;}         i,em{font-style:normal}     svg:not(:root){overflow:hidden}
img{vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;-webkit-tap-highlight-color:rgba(0,0,0,0);}   
a{color:#333;text-decoration: none;outline:none;} 
a:link {color:#333;} 
a:visited {color:#333;} 
a:hover {color:#c00;text-decoration:underline;}
a:active{blr:expression(this.onFocus=this.blur())}
a:focus {outline:none;-moz-outline:none;}
form{ width:300px;  margin:20px auto 0;}
h3{ font-weight:bold; margin:10px 0;}
p{ margin-bottom:10px;}
input{ vertical-align:middle; margin-left:10px; height:24px; line-height:24px; width:200px; padding-left:2px; border:1px #CCC solid;}
textarea{ vertical-align:middle; margin-left:10px; width:200px; height:50px; font:inherit; padding-left:2px; border:1px #CCC solid;}
.wrap-statistics{ visibility:hidden;}
.dn{ display:none;}   .db{ display:block;}
.finps{ width:200px; height:24px;line-height:24px; border:1px #C30 solid; padding:0 5px; color:#000;}
.oinps{width:200px; height:24px;line-height:24px; border:1px #CCC solid; padding:0 5px; color:#000;z-index:5;}
.ftext{ width:200px; height:50px; border:1px #C30 solid; padding:0 5px; color:#000;}
.otext{width:200px; height:50px; border:1px #CCC solid; padding:0 5px; color:#000;}
</style>
</head>
<body>
<form id="form1">
    <h3>通过input方式模拟placeholder</h3>
    <p><label for="username1">用户名:</label><input type="text" name="username1" class="tst oinps"  placeholder="请输入用户名" value="123" ></p>
    <p><label for="password1">密 码:</label><input type="password" name="password1" class="tst oinps" placeholder="请输入密码" value="" ></p>
    <p><label for="address1">地 址:</label><input type="text" name="address1"  placeholder="请输入地址" value="" ></p>
</form>
<form id="form2">
    <h3>通过textarea方式模拟placeholder</h3>
    <p><label for="remarks1">备 注:</label><textarea placeholder="请输入备注"  class="otext" id="remarks1"></textarea></p>
    <p><label for="remarks2">备 注:</label><textarea placeholder="请输入备注" class="otext" id="remarks2"></textarea></p>
    <p><label for="remarks3">备 注:</label><textarea id="remarks3"></textarea></p>
</form>
<script>
/**
 * @name placeHolder
 * @class 跨浏览器placeHolder,对于不支持原生placeHolder的浏览器,通过value或插入span元素两种方案模拟
 * @param {Object} obj 要应用placeHolder的表单元素对象  
 */
function readyplace(element, type, handler){
 if (element.addEventListener){
  element.addEventListener(type, handler, false);
 } else if (element.attachEvent){
  element.attachEvent("on" + type, handler);
 } else {
  element["on" + type] = handler;
 }
}
(function (window, undefined) {
var hasClass = function(elem,sClass)
{
    var sOldName=elem.className;
    if(sOldName)
    {
        sOldName=sOldName.split(‘ ‘);
        for(var i=0;i<sOldName.length;i++)
        {
            if(sOldName[i]==sClass)
            {
                return true;
            }
        }
    }
}
var addClass = function(elem,sClass)
{
    if(!hasClass(elem,sClass))
    {
        if(elem.className)
        {
            var sOldName=elem.className, blank = (sOldName != ‘‘) ? ‘ ‘ : ‘‘;
            elem.className=sOldName + blank + sClass;
        }
        else
        {
            elem.className=sClass;
        }
    }
}
var removeClass = function(elem,sClass)
{
    var sOldName=elem.className.split(‘ ‘);
    var sNewClass=‘‘;
    for(var i=0;i<sOldName.length;i++)
    {
        if(sOldName[i] && sOldName[i]!=sClass)
        {
            sNewClass+=sOldName[i]+‘ ‘;
        }
    }
    elem.className=sNewClass.replace(/(^\s+)|(\s+$)/g, ‘‘);
}
 var Place = (function() {
  return function(set){
   this.tagName    = set.tagName || "input" ;  
   this.placeattr  = set.placeattr || "placeholder" ;     
   this.isempty    = set.isempty ? true : false;
   this.focusCls   = set.focusCls || "finps";
   this.onblurCls  = set.onblurCls || "oinps";
   this.init();
  } 
    })();
 Place.prototype = {
  init : function() { 
   var elemTagName = document.getElementsByTagName(this.tagName);
   for(var i=0;i<elemTagName.length;i++){
    this.create(elemTagName[i],this.isempty);
   }  
  },
  create:function(obj,isShow){
   if (!obj.getAttribute(this.placeattr)) return;
   var getStyle = function(obj, prop) {
    if (obj.currentStyle) { //IE浏览器
     return obj.currentStyle[prop];
    } else if (window.getComputedStyle) { //W3C标准浏览器
     return document.defaultView.getComputedStyle(obj, null)[prop];
    }
    return null;
   };
   var defaultValue = obj.getAttribute(this.placeattr);
   var placeHolderCont = document.createTextNode(defaultValue);
   var REPX=/px|em|rem/;
   var pat=parseInt(getStyle(obj,"paddingTop").replace(REPX,‘‘)) || 0;
   var par=parseInt(getStyle(obj,"paddingRight").replace(REPX,‘‘)) || 0;
   var pab=parseInt(getStyle(obj,"paddingBottom").replace(REPX,‘‘)) || 0;
   var pal=parseInt(getStyle(obj,"paddingLeft").replace(REPX,‘‘)) || 0;
   
   var mat=parseInt(getStyle(obj,"marginTop").replace(REPX,‘‘)) || 0;
   var mar=parseInt(getStyle(obj,"marginRight").replace(REPX,‘‘)) || 0;
   var mab=parseInt(getStyle(obj,"marginBottom").replace(REPX,‘‘)) || 0;
   var mal=parseInt(getStyle(obj,"marginLeft").replace(REPX,‘‘)) || 0;
   
   var fontSize = getStyle(obj, ‘fontSize‘);
   if (!obj.getAttribute("id")) {
    var idFor = "place" +Math.floor(Math.random().toString().substr(2,8));
   }else{
    var idFor =obj.getAttribute("id");
   }
   obj.setAttribute("id", idFor);
            var LabelWrap = document.createElement(‘label‘);
       LabelWrap.setAttribute("for", idFor);
       LabelWrap.className = ‘placewrap‘;
                LabelWrap.style.cssText = ‘font-size:‘+fontSize+‘;position:absolute;cursor:text;text-indent:2px;z-index:5;top:‘+mat+‘px;left:‘+mal+‘px;padding:‘+pat+‘px ‘+par+‘px ‘+pab+‘px ‘+pal+‘px;color:#A9A9A9;‘;
    LabelWrap.style.width = obj.offsetWidth - (parseInt(getStyle(obj, ‘marginLeft‘), 10)||0) + ‘px‘;
    LabelWrap.style.lineHeight = obj.nodeName.toLowerCase() == ‘textarea‘ ? ‘‘: obj.offsetHeight-pat-pab + ‘px‘;
   var placebox=document.createElement("div");
    placebox.className="labelwraps";
    placebox.style.cssText=‘position:relative;visibility:visible;z-index:1;display:inline-block;‘;
    obj.parentNode.insertBefore(placebox,null);
    LabelWrap.appendChild(placeHolderCont);
    placebox.appendChild(LabelWrap); 
    placebox.appendChild(obj); 
    obj.removeAttribute(this.placeattr);
            LabelWrap.onclick = function() { obj.focus();  };
   LabelWrap.style.display = obj.value == ‘‘ ? ‘block‘: ‘none‘;
   var changeHandler = function() {
    LabelWrap.style.display = obj.value != ‘‘ ? ‘none‘: ‘block‘;
   };
            var that=this;
   if(!isShow){
    obj.onclick = function() {
     if(obj.value == defaultValue && obj.value != ‘‘){
      LabelWrap.style.display =‘block‘;
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }else {
      LabelWrap.style.display =‘none‘;
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }
    }
    obj.oninput = function() {
     if(obj.value != ‘‘){
      LabelWrap.style.display =‘none‘;
     }else{
      LabelWrap.style.display =‘block‘;
     } 
    }
    obj.onblur = function() {
     if(obj.value != ‘‘){
      LabelWrap.style.display =‘none‘;
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }else{
      LabelWrap.style.display =‘block‘;
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }
    }
    //obj.onblur();
   }else{
    obj.onclick = function() {
     if(obj.value == defaultValue && obj.value != ‘‘){
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }else {
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }
    };
    obj.onblur = function() {
     if(obj.value != ‘‘){
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }else{
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }
    };
    if (typeof(obj.oninput) == ‘object‘) {
     obj.addEventListener("input", changeHandler, false);
    } else {
     obj.onpropertychange = changeHandler;
    }
   };
   return this;
  }
 }
 var placeholder = function(options) { new Place(options); }
 window.placeholder = placeholder;
 return placeholder;
})(window);
readyplace(document, ‘readystatechange‘, function(){
    placeholder({focusCls:‘finps‘,onblurCls:‘oinps‘,isempty:false});
 placeholder({tagName:‘textarea‘,focusCls:‘ftext‘,onblurCls:‘otext‘,isempty:true});
})
</script>
</body>
</html>

让IE支持placeholder属性,跨浏览器placehoder

时间: 2024-08-25 07:26:33

让IE支持placeholder属性,跨浏览器placehoder的相关文章

在IE8等不支持placeholder属性的浏览器中模拟placeholder效果

placeholder是一个很有用的属性,可以提示用户在input框中输入正确的内容,但是IE8以及IE8一下的浏览器不支持该属性,我们可以使用js来模拟相似的效果.下面直接上代码: <!doctype html> <html> <header> <meta charset="utf-8"> <title>placeholder</title> <style type="text/css"

基于jQuery的让非HTML5浏览器支持placeholder属性的代码(转)

效果图:http://code.google.com/p/jquery-placeholder-js/ 演示代码:http://demo.jb51.net/js/2011/jqueryplaceholder/打包下载:http://xiazai.jb51.net/201105/yuanma/jqueryplaceholder.rar 基于jQuery的让非HTML5浏览器支持placeholder属性的代码(转),布布扣,bubuko.com

在IE8及以下的浏览器中,不支持placeholder属性的解决办法

以下代码解决了在IE8及以下浏览器中不支持placeholder属性. 原理:将placeholder的值作为内容写入控件,并添加控件事件来进行模拟. ;(function(){ if( !('placeholder' in document.createElement('input')) ){ // 匹配 除type=password以外所有input.textarea $('input[placeholder][type!=password],textarea[placeholder]').

让IE低版本浏览器也支持placeholder属性

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />     <title>让IE低版本浏览器也支持placeholder属性</title>    

跨浏览器placehoder

<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>跨浏览器placehoder</title> <meta name="author" content="ifrans.cn" /> <meta name="description" content="跨浏览

jQuery placeholder插件 让IE也能够支持placeholder属性

jQuery placeholder插件 让IE也能够支持placeholder属性 案例:整搜索框,需要默认占位符为“请输入关键词”,获取焦点时,占位符消失或不可用(不影响正常输入),丢失焦点后,若用户无内容输入,占位符继续出现,继续占位.这种代码我想前端们已经很容易就写出来了吧,现在HTML5原生就有这个“placeholder”属性,效果与上边案例描述的一样(各支持的浏览器内部表现可能不一致,但是作用是一致的),那么这一属性该怎么优雅降级到支持所有现代浏览器呢?答案还是脚本即JavaScr

[原创]Web前端开发——让ie 7 8支持placeholder属性

今天在写页面的时候,测试低版本浏览器时,发现input写的placeholder显示的是空白,所以特意写了一个普遍试用的方法来让低版本浏览器支持这个属性. 博主建了一个技术共享qq群:164858883,因为目前人数还比较少,活跃度还不是很高,希望有和我一样想法的,有志于技术共享的技术宅,富有逗比精神的程序猿能一起加入,一起探讨和分享,一起创造更大的进步.当然,妹纸程序猿更受欢迎哟.^_^ 一般情况下,我们解决这个问题呢会使用下面这种方法. 1 <input onfocus="if (va

低版本浏览器支持placeholder属性

if (!placeholderSupport()) { //判断浏览器是否支持 placeholder $('[placeholder]').focus(function() { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); input.removeClass('placeholder'); } if (input[type = 'password'].val() == i

关于IE9以下的IE浏览器不支持placeholder属性的解决方案

页面元素结构 页面样式 页面JS 页面效果 综上,可能JS需要根据个人稍作调整,还有增加个性化的操作等..