檢查出這個完整的解決方案:
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(){
var keyMap = {
'(': ')',
'[': ']',
'<': '>',
'{': '}',
'"': '"',
'\'': '\''
};
$('.editor').keypress(function(e){
if(this.selectionStart == this.selectionEnd)
return true;
e.preventDefault();
var txtCur = $(this).val();
var left = txtCur.substring(0, this.selectionStart);
var middle = txtCur.substring(this.selectionStart, this.selectionEnd);
var right = txtCur.substring(this.selectionEnd);
var cur = String.fromCharCode(e.keyCode);
if(keyMap[cur])
middle = cur + middle + keyMap[cur];
else
middle = cur;
var pos = (left+middle).length;
$(this).val(left+middle+right);
this.setSelectionRange(pos,pos);
});
});
})(jQuery);
</script
</head>
<body>
<textarea class="editor">abcdefghijklmnopqrstuvwxyz</textarea>
</body>
</html>