原理嘛: 咱們對全部 textarea 元素綁定 onkeydown 事件,截獲tab按鍵行爲,經過js操做文本實現縮進,阻止默認的tab事件。this
藉助於jQuery,實現了一下:code
<!-- lang: js --> //textarea支持tab縮進 $("textarea").on('keydown',function(e){ if(e.keyCode == 9){ e.preventDefault(); var indent = ' '; var start = this.selectionStart; var end = this.selectionEnd; var selected = window.getSelection().toString(); selected = indent + selected.replace(/\n/g,'\n'+indent); this.value = this.value.substring(0,start) + selected + this.value.substring(end); this.setSelectionRange(start+indent.length,start+selected.length); } })
支持多行縮進事件