vue项目解决IE9不支持placeholder

简书大佬 vue项目解决IE9不支持placeholder
https://www.jianshu.com/p/1c239e4c176c
通过vue的自定义全局指令 Vue.directive 来控制。
由于项目中使用到了elementUi ,所以以解决elementUi组件的input为例

<el-input v-support v-model="value" placeholder="请输入姓名"></el-input>

自定义指令代码

    Vue.directive("support", {
        inserted: function (el, binding, vnode) {
            console.log(el, 'el')
            // 如果兼容placeholder则终止
            if (("placeholder" in document.createElement("input"))) {
                return;
            }
            // select暂时不支持(input为只读状态时)
            var isReadOnly = el.getAttribute("readOnly");
            if (isReadOnly) return

            // 由于第三方input组件都包了一个外层
            var input = el.querySelector("input");
            var placeholder = input.getAttribute("placeholder");
            var span = document.createElement("span");

            // .ie-placeholder 可根据类名自定义样式
            span.className = "ie-placeholder";
            span.innerText = placeholder;
            // 位置设置
            span.style.left = input.offsetLeft + '4' + "px";
            input.parentNode.style.position = "relative";
            input.parentNode.appendChild(span);
            el.addEventListener('click', function (event) {
                if (event.target.nodeName == 'SPAN') {
                    // span.style.display = "none";
                    input.focus()
                }
            })
            span.addEventListener('click', function (event) {
                // span.style.display = "none";
                input.focus()
            })
            input.onblur = function (event) {
                if (!event.target.value) {
                    span.style.display = "inline";
                }
            };
            input.oninput = function (event) {
                if (event.target.value) {
                    span.style.display = "none";
                } else {
                    span.style.display = "inline";
                }
            }
        },

        // 开始更新
        unbind: function (el) {
            var input = el.querySelector("input");
            input.onfocus = input.onblur = input.oninput = null;
        }
    })
可根据ie-placeholder修改css样式

```javascript
.ie-placeholder {
    font-size: 14px;
    color: #9c9c9c;
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值