参考文章链接
如果是 .html的项目,在需要的页面引入jquery后再引入placeholder.js插件即可解决
因为我是vue+elementUI的项目,所以不会每次切换菜单都刷新浏览器,所以整理了一下vue里的用法
在这里也需要引入jquery文件,不然可能会报错,在index.html里引入jquery就可以了
接下来就是vue里的用法了
首先在公共js文件里新建placeholder.js文件,输出一个PlaceholderInit函数
//解决ie下 input 的placeholder不显示问题
export function PlaceholderInit() {
return jQuery(function() {
var placeholderfriend = {
focus: function(s) {
s = $(s)
.hide()
.prev()
.show()
.focus();
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue.replace("placeholderfriend", ""));
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue.replace("placeholderfriend", ""));
}
}
};
//判断是否支持placeholder
function isPlaceholer() {
var input = document.createElement("input");
return "placeholder" in input;
}
//不支持的代码
if (!isPlaceholer()) {
$(function() {
var form = $(this);
var elements = form.find("input[type='text'][placeholder]");
elements.each(function() {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (pValue) {
if (sValue == "") {
s.val(pValue);
}
}
});
elements.focus(function() {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (sValue && pValue) {
if (sValue == pValue) {
s.val("");
}
}
});
elements.blur(function() {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (!sValue) {
s.val(pValue);
}
});
var elementsPass = form.find("input[type='password'][placeholder]");
elementsPass.each(function(i) {
var s = $(this);
var pValue = s.attr("placeholder");
var sValue = s.val();
if (pValue) {
if (sValue == "") {
var html = this.outerHTML || "";
html = html
.replace(
/\s*type=(['"])?password\1/gi,
" type=text placeholderfriend"
)
.replace(/\s*(?:value|on1[a-z]+|name)(=(['"])?\S*\1)?/gi, " ")
.replace(
/\s*placeholderfriend/,
" placeholderfriend value='" +
pValue +
"' " +
"οnfοcus='placeholderfriendfocus(this);' "
);
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue + "placeholderfriend");
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue + "placeholderfriend");
}
s.hide();
s.after(html);
}
}
});
elementsPass.blur(function() {
var s = $(this);
var sValue = s.val();
if (sValue == "") {
var idValue = s.attr("id");
if (idValue) {
s.attr("id", idValue + "placeholderfriend");
}
var clsValue = s.attr("class");
if (clsValue) {
s.attr("class", clsValue + "placeholderfriend");
}
s.hide()
.next()
.show();
}
});
});
}
window.placeholderfriendfocus = placeholderfriend.focus;
});
}
在需要显示placeholder的页面解构出PlaceholderInit函数
import { PlaceholderInit } from '@/utils/placeholder'
在页面显示之前调用这个函数,这样当前页面需要显示placeholder的地方在页面进来的时候就会正常显示
PlaceholderInit();
如果有新增弹框的输入框页需要显示placeholder,在打开新增弹框的时候同样调用此函数
别的需要的地方使用方法也一样