前言
公司要求写一个搬家页面 里面全部是input框 起初没考虑到兼容问题 直接用input标签里面的 placeholder属性
测试的时候 发现ie9没有 于是开始寻求解决方案 最后在不改变源代码的基础上 选择用js只对ie9 及以下进行处理
源码
HTML
<div class="test-item">
<label for="pwd">密码:</label>
<input class=" password" id="pwd" type="password" placeholder="请输入密码">
<span class="pwd-place"></span>//用于模仿placeholder
</div>
CSS
.pwd-place {
position: absolute;
top: 0;
left: 100px;
width: 100%;
height: 100%;
font-size: 12px;
}
/**
* 兼容placeholer方法
* @param {dom对象} el 传入需要代替的span标签
* @return {null} 暂时好像没有返回值
*/
function placeholder(el) {
/**
* 检测时候需要方法兼容
* @returns {boolean}
*/
function isPlaceholer() {
var input = document.createElement("input");//新建一个input
return "placeholder" in input;
}
var $el = $(el);
//在不支持placeholder属性的情况下
if (isPlaceholer() == false && !('placeholder' in document.createElement('input'))) {
$('input[placeholder]').css("color", "#999").each(function () {
var that = $(this),
text = that.attr('placeholder'); //获取input标签中的placeholder中的文字
if (that.val() === "") { //如果input标签为空
that.val(text).addClass('placeholder'); //如果不是密码输入placeholder的内容并且添加类名placeholder
}
that.focus(function () { //input获得光标焦点后,输入框中的内容清空
console.log(that);
that.css("color", "#000")
if ($el.html() == text) { //如果传入的dom元素的文本内容等于placeholder的内容
$el.html(""); //清空
}
if (that.val() === text) { //如果input的值等于placeholder内容
that.val("").removeClass('placeholder'); //清空并且移出placeholder属性
}
})
.blur(function () { //光标焦点离开输入框时,给输入框添加提示内容
if (that.val() === "") { //如果输入框没有文字内容
that.val(text).addClass('placeholder'); //输入place内容 并且增加属性 placeholder
that.css("color", "#999")
}
})
// .closest('form').submit(function () { //查找上层元素提交的话
// if (that.val() === text) { //如果里面文字内容等于传入的值 则置空
// that.val(''); //TODO 这里我用不到 但是很重要
// }
// });
$("#autoMove").on("mousedown", function () { //这个是我的 如果点击提交 如果val的值等于placeholder 那么清空val
console.log(that);
if (that.val() === text) {
that.val('');
}
})
});
}
}
//上来就执行 相当于 window.onload
$(document).ready(function () {
placeholder(".pwd-place")
});
后记
里面标注我都写的很清楚
核心原理是用input的value值取代placeholder
还有很多方法可以做到 比如用 行内标签 代替placeholder
甚至可以用 图片 代替placeholder
至于怎么用 需要你针对你的项目稍作调整