让IE支持placeholder属性

本文介绍了一种在Internet Explorer浏览器中实现HTML5 placeholder属性的方法。通过使用jQuery库和自定义JavaScript脚本,此方案使IE6至IE9版本能够支持placeholder功能。演示代码展示了如何为文本框设置占位符文本,当文本框获取焦点或输入内容时,占位符将自动隐藏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

placeholder 属性提供可描述输入字段预期值的提示信息
该提示会在输入字段为空时显示,并会在字段获得焦点时消失。
但placeholder不支持IE10以下版本
在页面中只需引入placeholder.js即可

/*
 * jQuery placeholder, fix for IE6,7,8,9
 * @website itmyhome.com
 */
var JPlaceHolder = {
    //检测
    _check : function(){
        return 'placeholder' in document.createElement('input');
    },
    //初始化
    init : function(){
        if(!this._check()){
            this.fix();
        }
    },
    //修复
    fix : function(){
        jQuery(':input[placeholder]').each(function(index, element) {

            var self = $(this), txt = self.attr('placeholder');
            self.wrap($('<div></div>').css({position:'relative', zoom:'1', border:'none', background:'none', padding:'none', margin:'none'}));
            var pos = self.position(), h = self.outerHeight(true), paddingleft = self.css('padding-left');

            var holder = $('<span></span>').text(txt).css({position:'absolute', left:pos.left, top:pos.top, height:h, lienHeight:h, paddingLeft:paddingleft, color:'#aaa'}).appendTo(self.parent());
            self.focusin(function(e) {
                holder.hide();
            }).focusout(function(e) {
                if(!self.val()){
                    holder.show();
                }
            });
            holder.click(function(e) {
                holder.hide();
                self.focus();
            });
        });
    }
};
//执行
jQuery(function(){
    JPlaceHolder.init();    
});

使用方法:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head> 
    <title>IE支持placeholder</title> 
    <script type="text/javascript" src="jquery.min.js"></script> 
    <script type="text/javascript" src="placeholder.js"></script> 
 </head> 
   <body> 
    <table> 
       <tbody>
          <tr> 
             <td> <input type="text" name="username" placeholder="Username" /> </td> 
          </tr> 
          <tr> 
             <td> <input type="password" name="password" placeholder="Password" /> </td> 
          </tr> 
       </tbody>
    </table>  
   </body>
</html>

如果要修改placeholder内的文字样式 可在placeholder.js里<span></span>中添加style属性,如:

<span style="font-size: 13px;padding-top: 8px;"></span>

这样在IE中就会显示正常

这里写图片描述这里写图片描述

因为本例中的input文本框使用了bootstrap 所以行高会高一点,如果是普通的input 则无需添加style属性

演示:ie-placeholder

作者:itmyhome

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值