提交 | 用户 | 时间
|
1ac2bc
|
1 |
(function($) |
懒 |
2 |
{ |
|
3 |
/** |
|
4 |
* Auto-growing textareas; technique ripped from Facebook |
|
5 |
* |
|
6 |
* http://github.com/jaz303/jquery-grab-bag/tree/master/javascripts/jquery.autogrow-textarea.js |
|
7 |
*/ |
|
8 |
$.fn.autogrow = function(options) |
|
9 |
{ |
|
10 |
return this.filter('textarea').each(function() |
|
11 |
{ |
|
12 |
var self = this; |
|
13 |
var $self = $(self); |
|
14 |
var minHeight = $self.height(); |
|
15 |
var noFlickerPad = $self.hasClass('autogrow-short') ? 0 : parseInt($self.css('lineHeight')) || 0; |
|
16 |
|
|
17 |
var shadow = $('<div></div>').css({ |
|
18 |
position: 'absolute', |
|
19 |
top: -10000, |
|
20 |
left: -10000, |
|
21 |
width: $self.width(), |
|
22 |
fontSize: $self.css('fontSize'), |
|
23 |
fontFamily: $self.css('fontFamily'), |
|
24 |
fontWeight: $self.css('fontWeight'), |
|
25 |
lineHeight: $self.css('lineHeight'), |
|
26 |
resize: 'none', |
|
27 |
'word-wrap': 'break-word' |
|
28 |
}).appendTo(document.body); |
|
29 |
|
|
30 |
var update = function(event) |
|
31 |
{ |
|
32 |
var times = function(string, number) |
|
33 |
{ |
|
34 |
for (var i=0, r=''; i<number; i++) r += string; |
|
35 |
return r; |
|
36 |
}; |
|
37 |
|
|
38 |
var val = self.value.replace(/</g, '<') |
|
39 |
.replace(/>/g, '>') |
|
40 |
.replace(/&/g, '&') |
|
41 |
.replace(/\n$/, '<br/> ') |
|
42 |
.replace(/\n/g, '<br/>') |
|
43 |
.replace(/ {2,}/g, function(space){ return times(' ', space.length - 1) + ' ' }); |
|
44 |
|
|
45 |
// Did enter get pressed? Resize in this keydown event so that the flicker doesn't occur. |
|
46 |
if (event && event.data && event.data.event === 'keydown' && event.keyCode === 13) { |
|
47 |
val += '<br />'; |
|
48 |
} |
|
49 |
|
|
50 |
shadow.css('width', $self.width()); |
|
51 |
shadow.html(val + (noFlickerPad === 0 ? '...' : '')); // Append '...' to resize pre-emptively. |
|
52 |
$self.height(Math.max(shadow.height() + noFlickerPad, minHeight)); |
|
53 |
} |
|
54 |
|
|
55 |
$self.change(update).keyup(update).keydown({event:'keydown'},update); |
|
56 |
$(window).resize(update); |
|
57 |
|
|
58 |
update(); |
|
59 |
}); |
|
60 |
}; |
|
61 |
})(jQuery); |