在 Textarea 中单击Tab键时,会切换控件焦点,而不是在 Textarea 中输入制表符。如何才能实现制表符的输入呢?
看代码:
| 1 | function insertTabToTextarea(event){ |
| 2 | event = event ? event : window.event; |
| 3 | if (event.keyCode == 9) { |
| 4 | event.returnValue = false; |
| 5 | var textEl = $("ads_ad_content"); |
| 6 | var text = ‘\t‘; |
| 7 | /**//*@cc_on |
| 8 | @set @ie = true |
| 9 | @if (@ie) |
| 10 | textEl.focus(); |
| 11 | document.selection.createRange().text = text; |
| 12 | @else @*/ |
| 13 | if (textEl.selectionStart || textEl.selectionStart == ‘0‘) { |
| 14 | var startPos = textEl.selectionStart; |
| 15 | var endPos = textEl.selectionEnd; |
| 16 | textEl.value = textEl.value.substring(0, startPos) |
| 17 | + text |
| 18 | + textEl.value.substring(endPos, textEl.value.length); |
| 19 | } else { |
| 20 | textEl.value += text; |
| 21 | } |
| 22 | textEl.selectionStart = endPos+1; |
| 23 | textEl.selectionEnd = endPos+1; |
| 24 | /**//*@end @*/ |
| 25 | return false; |
| 26 | } |
| 27 | } |
Line 3 : Tab键的keyCode值是9,这是根据键值判断输入是否是Tab键;
Line 22-23: 表示插入制表符后光标位于插入tab键后。