1. 程式人生 > 實用技巧 >相容ie9的placeholder(vue自定義指令)

相容ie9的placeholder(vue自定義指令)

const supportIE = {
install:function (Vue) {
Vue.directive('support', {
inserted: function (el) {
if (('placeholder' in document.createElement('input'))) {
return;
}
if (/^el/.test(el.className)) {
el = el.querySelector('[placeholder]');
}
let placeholder = el.getAttribute('placeholder') || '請輸入';
let span = document.createElement('span');
span.className = 'ie-placeholder';
span.innerText = placeholder;
span.style.left = el.offsetLeft + 25 + 'px';
// el.parentNode.style.position = 'relative'
el.insertAdjacentElement('afterend', span);
span.onclick = function (event) {
el.focus();
}
el.onfocus = function (event) {
if (event.target.value) {
span.style.display = 'none';
}
};
el.onblur = function (event) {
if (!event.target.value) {
span.style.display = 'inline';
}
};
el.oninput = function (event) {
if (event.target.value) {
span.style.display = 'none';
} else {
span.style.display = 'inline';
}
}
},
unbind: function (el) {
el.onfocus = el.onblur = el.oninput = null;
}
})
}
}

export default supportIE

使用方式: