jquery.placeholder.js
3.45 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
$.fn.placeholder = function(option, callback) {
var settings = $.extend({
word: '',
color: '#999',
evtType: 'focus',
zIndex: 20,
diffPaddingLeft: 3
}, option);
function bootstrap($that) {
// some alias
var word = settings.word;
var color = settings.color;
var evtType = settings.evtType;
var zIndex = settings.zIndex;
var diffPaddingLeft = settings.diffPaddingLeft;
// default css
var width = $that.outerWidth();
var height = $that.outerHeight();
var fontSize = $that.css('font-size');
var fontFamily = $that.css('font-family');
var paddingLeft = $that.css('padding-left');
// process
paddingLeft = parseInt(paddingLeft, 10) + diffPaddingLeft;
// redner
var $placeholder = $('<span class="placeholder">');
$placeholder.css({
position: 'absolute',
zIndex: '20',
color: color,
width: (width - paddingLeft) + 'px',
height: height + 'px',
fontSize: fontSize,
paddingLeft: paddingLeft + 'px',
fontFamily: fontFamily
}).text(word).hide();
// 位置调整
move();
// textarea 不加line-heihgt属性
if ($that.is('input')) {
$placeholder.css({
lineHeight: height + 'px'
});
}
$placeholder.appendTo(document.body);
// 内容为空时才显示,比如刷新页面输入域已经填入了内容时
var val = $that.val();
if (val == '' && $that.is(':visible') ) {
$placeholder.show();
}
function hideAndFocus() {
$placeholder.hide();
$that[0].focus();
}
function move() {
var offset = $that.offset()
var top = offset.top
var left = offset.left
$placeholder.css({
top: top,
left: left
});
}
function asFocus() {
$placeholder.click(function() {
hideAndFocus();
// 盖住后无法触发input的click事件,需要模拟点击下
setTimeout(function(){
$that.click();
}, 100);
})
// IE有些bug,原本不用加此句
$that.click(hideAndFocus);
$that.blur(function() {
var txt = $that.val();
if (txt == '') {
$placeholder.show();
}
});
}
function asKeydown() {
$placeholder.click(function() {
$that[0].focus();
});
}
if (evtType == 'focus') {
asFocus();
} else if (evtType == 'keydown') {
asKeydown();
}
$that.keyup(function() {
var txt = $that.val();
if (txt == '') {
$placeholder.show();
} else {
$placeholder.hide();
}
});
// 窗口缩放时处理
$(window).resize(function() {
move();
});
// cache
$that.data('el', $placeholder);
$that.data('move', move);
}
return this.each(function() {
var $elem = $(this);
bootstrap($elem);
if ($.isFunction(callback)) {
callback($elem);
}
});
}