开发一个项目的时候为了美观和用户体验用到了input标签的placeholder属性,但是这个属性是html5中的,所以低版本的IE浏览器不支持。于是在百度找了一些解决方法,找了好几个都不是那么完美,最后决定将其中的一个拿来完善一下。
完善后的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
jQuery.fn.placeholder =
function
(){
var
i = document.createElement(
'input'
),placeholdersupport =
'placeholder'
in
i;
if
(!placeholdersupport){
var
inputs = jQuery(
this
);
inputs.each(
function
(){
var
input = jQuery(
this
),
text = input.attr(
'placeholder'
),
pdl = 0,height = input.outerHeight(),
width = input.outerWidth(),
placeholder = jQuery(
'<span class="phTips">'
+text+
'</span>'
);
try
{
pdl = input.css(
'padding-left'
).match(/\d*/i)[0] * 1;
}
catch
(e){
pdl = 5;
}
placeholder.css({
'margin-left'
: -(width-pdl),
'height'
:height,
'line-height'
:height+
"px"
,
'position'
:
'absolute'
,
'color'
:
"#cecfc9"
,
'font-size'
:
"12px"
});
placeholder.click(
function
(){
input.focus();
});
if
(input.val() !=
""
){
placeholder.css({display:
'none'
});
}
else
{
placeholder.css({display:
'inline'
});
}
placeholder.insertAfter(input);
input.keydown(
function
(e){
placeholder.css({display:
'none'
});
});
input.keyup(
function
(e){
if
(jQuery(
this
).val() !=
""
){
placeholder.css({display:
'none'
});
}
else
{
placeholder.css({display:
'inline'
});
}
});
});
}
return
this
;
};
|
其中第33到35行代码是我加上去的,原来的代码可以用,但是键入的时候提示内容隐藏有点反应慢,分析代码后发现是对keyup引起了,增加keydown后就几近完美了。
使用时将上面的代码保存为placeholder.jquery.js.
用法:
首先引入jquery
1
|
<
script
src
=
"//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
></
script
>
|
然后引入我们的插件
1
|
<script src=
"/js/placeholder.jquery.js"
></script>
|
最后写上调用代码就可以了
1
2
3
4
5
|
<
script
>
$(document).ready(function(e) {
$('input[placeholder]').placeholder();
});
</
script
>
|
代码参考:http://blog.163.com/yhwwen@126/blog/static/17046885320135915529172/
在此感谢代码作者!