ie8怎么用placeholder
的有关信息介绍如下:
placeholder是HTML5新增的属性,代替了onfocus,onblur方法,并且比它们更方便。但是ie8并不支持该属性,那么如何用JavaScript来解决ie8下placeholder的兼容性呢?
placeholder作为input的新增属性,要想让它兼容ie8,需解决以下两点:
1、在ie8不支持该属性
解决思路:如果浏览器不支持placeholder属性,那我们就模仿出placeholder的属性,添加在input上,然后将placeholder属性的值赋给input的value值
2、input的type属性值为password时,密码是不可见的
解决思路:新增一个标签,模仿placeholder的属性
首先,将form表单做出来,给input添加placeholder属性,把的基本结构写好,代码如下:
HTML:
CSS:
.test-item {
position: relative;
margin: 10px;
}
效果如图:
根据第一步中的思路,对于不支持placeholder属性的浏览器,我们需要创建一个模仿placeholder属性的input,然后把这个模仿的placeholder属性值赋给新建的input,所以,在html基本结构上,要添加一些内容
html:
CSS:
.pwd-place {
position: absolute;
top: 0;
left: 100px;
width: 100%;
height: 100%;
font-size: 12px;
}
通过js来实现兼容,引入jQuery,在head标签内添加一下代码:
然后在body中添加以下js代码:
function placeholder(el){
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],textarea[placeholder]').each(function(){
var that = $(this),
text= that.attr('placeholder');
if(that.val()===""){
if(that.attr("type") == "password"){
$el.html("请输入密码");
}else {
that.val(text).addClass('placeholder');
}
}
that.focus(function(){//input获得光标焦点后,输入框中的内容清空
if($el.html() == text){
$el.html("");
}
if(that.val()===text) {
that.val("").removeClass('placeholder');
}
})
.blur(function(){//光标焦点离开输入框时,给输入框添加提示内容
if(that.val()==="") {
if (that.attr("type") == "password") {
$el.html("请输入密码");
}else {
that.val(text).addClass('placeholder');
}
}
})
.closest('form').submit(function(){
if(that.val() === text){
that.val('');
}
});
});
}
}
$(document).ready(function() {
placeholder(".pwd-place")
});
具体步骤思路,想看代码中的注释!



