这个代码的作用是让textarea也能输入tab,并可以像代码编辑器一样能自动缩进。
废话不多说了,直接上Demo:
https://codepen.io/Wu23333/pen/MWwYmmK
var textarea_id = "text";
(function($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
}else
if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$(document).keydown(function(e){
text=document.getElementById(textarea_id);
if(e.which == 9){
var cursor_pos = $(text).getCursorPosition();
$(text).val($(text).val().slice(0,cursor_pos) + '\t' + $(text).val().slice(cursor_pos));
text.focus();
text.setSelectionRange(cursor_pos+1, cursor_pos+1);
return false;
}
if(e.which == 13){
var cursor_pos = $(text).getCursorPosition();
var notelines = $(text).val().slice(0,cursor_pos).split('\n');
var listline = notelines[notelines.length-1];
var n = 0;
while(listline[n] == '\t'){
n+=1;
}
$(text).val($(text).val().slice(0, cursor_pos)+'\n'+$(text).val().slice(cursor_pos));
for (i=n; i>0; i--){
$(text).val($(text).val().slice(0, cursor_pos+1)+'\t'+$(text).val().slice(cursor_pos+1));
}
text.focus();
text.setSelectionRange(cursor_pos + n+1, cursor_pos + n+1);
return false;
}
});
您好。我在git@oschina那里留意到你的项目,我和香港几个朋友的团队新上线了一个PaaS服务,叫CNPaaS,是一个用git极简部署web项目的服务,想邀请您使用: http://www.cnpaas.io 。我们正在寻找种子用户,目前注册注册是限量开放的,因为我们希望针对您的需求做足够的优化先。遇到什么问题都向我反馈,或者联系网站上的联系方式。谢谢!