placeholder是一个很实用的Html 5属性,但是该属性在低版本的IE下是无效的,本文给出placeholder属性在 IE中失效的解决办法。
在页面设计中,表单的设计需要提示性的词语来引导用户使用,最常见的的就是使用<input>标签placeholder属性,只可惜这个HTML 5属性在低版本的IE下会失效,那该怎么办呢?
先来了解下placeholder
placeholder 属性提供可描述输入字段预期值的提示信息(hint)。该提示会在输入字段为空时显示,并会在字段获得焦点时消失。
如:
<form action="xxx.php" method="get"> <input type="search" name="username" placeholder="用户名" /> </form>
用户在使用表单的时候就会看到“用户名”这样的提示,在用户点击输入框时提示文字消失,非常的实用。但是该效果在IE下会失效,如果是多个输入框的话,没有提示文字,对用户十分的不友好。
只需要使用以下js代码,就可以解决placeholder属性在IE中失效了。
<script type="text/javascript">
;(function($){
$.fn.placeholder = function(options){
var opts = $.extend({}, $.fn.placeholder.defaults, options);
var isIE = document.all ? true : false;
return this.each(function(){
var _this = this,
placeholderValue =_this.getAttribute("placeholder"); //缓存默认的placeholder值
if(isIE){
_this.setAttribute("value",placeholderValue);
_this.onfocus = function(){
$.trim(_this.value) == placeholderValue ? _this.value = "" : '';
};
_this.onblur = function(){
$.trim(_this.value) == "" ? _this.value = placeholderValue : '';
};
}
});
};
})(jQuery);
</script>
然后设置需要支持此功能的元素。
<script type="text/javascript">
$("input").placeholder();
</script>
注意:此代码基于jquery库,所以使用前请先引入jquery库文件。





粤公网安备 44040402000065号
不懂了。来看看。
不错,博主对HTML/CSS研究颇深呀!
@明月学习笔记Blog: 还好吧,毕竟吃饭的家伙,哈哈
@飞鸟: 为啥我的没有用,有哪里是需要更改的吗