最近做项目发现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>