/*html*/
<div class="form-group">
<label>手机号码</label>
<input type="text" class="form-control phone-num" name="phone-num" placeholder="手机号码">
</div>
/*js*/
function placeholderForIe9(label,input){
/*检测浏览器是否支持placeholder,这里直接是判断是否是IE9,也可以使用其他方法判定*/
if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE9.0"){
$(label).parents(".form-group").css("position","relative");
for(i=0;i<$(label).length;i++){
var left = parseInt($(label).eq(i).siblings("input").css("paddingLeft"))+10+"px";
var top = $(label).eq(i).css("lineHeight");
$(label).eq(i).css({
"position":"absolute",
"top":top,
"left":left,
"opacity":"0.5",
"cursor":"text",
});
}
$(input).focus(function(){/*聚焦事件*/
$(this).siblings("label").css({
"display":"none",/*去除*/
})
});
$(input).blur(function(){
/*失去焦点事件,判断input框内是否已经有内容,没有的话还原。有的话去除*/
if($(this).val().length == 0){
$(this).siblings("label").css({
"display":"block",
})
}else{
$(this).siblings("label").css({
"display":"none",
})
}
});
$(label).click(function(){
/*由于label在input框的上层,所以设置label的点击事件,让它触发input的焦点事件*/
$(this).siblings(input).trigger("focus");
})
}else{
/*支持placeholder的情况下就把label去掉。*/
$(label).css("display","none");
}
}
基本思路。当检测到浏览器不支持placeholder时,让label绝对定位于form-group,然后再做位置调整即可。
如果想既要label又想要placeholder,可以使用别的标签比如<p>
代替上面的label。