IE9兼容placeholder

最近做项目发现IE9不支持placeholder属性,故而做兼容,在此做一个记录。

解决方案:先检查浏览器是否支持placeholder属性,如果支持,则不做处理;如果不支持,且placeholder有值的情况下,生成一个label标签覆盖在原来input的位置,然后再根据input的情况对label标签显示或隐藏。

效果如下图:

demo如下(由于宽度有限,对某些代码做了换行处理):

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="UTF-8">

<title>IE9兼容placeholder</title>

<style>

input{

    display: block;

    margin-bottom: 20px;

}

.self-placeholder{

    position: absolute;

    display: block;

    color: #bbb;

    font-size: 12px;

    padding-left: 10px;

    overflow: hidden;

    pointer-events: none;

    background: none;

    cursor: text;

}

</style>

<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

</head>

<body>

<div id="app-container">

    <input type="text" name="input1" id="input1" placeholder="请输入标题">

    <input type="text" name="input2" id="input2" placeholder="请输入文章">

</div>

</body>

<script type="text/babel">

placeholderShow();

function placeholderShow(wrap) {

    var supportPlaceholder = 'placeholder' in document.createElement('input');

    if(!supportPlaceholder) {

        $(wrap || "#app-container").off('keyup change input propertychange').on('keyup change input propertychange', 'input[placeholder]', function() {

            if(/^\s*$/.test(this.value)) {

                $(this).siblings('.js-label-placeholder').show();

            }else {

                $(this).siblings('.js-label-placeholder').hide();

            }

        });

        $('input[placeholder]').each(function() {

            const text = $(this).attr('placeholder'),

            $parent = $(this).parent(),

            top = this.offsetTop,

            left = this.offsetLeft,

            height = this.offsetHeight,

            width = this.offsetWidth;

            let id = this.id;

            if(!id) {

                id = `js-placeholder-${this.name}`;

                this.id = id;

            }

            if(text) {

                $parent.append(`<label for="${id}" style="text-align:left;top:${top}px;left:${left}px;height:${height}px;width:${width - 10}px;line-height:${height}px" class="self-placeholder js-label-placeholder">${text}</label>`)

            }

        })

    }

}

</script>

</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值