示例代码用ES6编写
创建Textarea类
// js文件名 Textarea.js
export class Textarea {
constructor (textarea) {
this.textarea = textarea
}
/**
* tab 缩进
*/
tabIndent () {
this.on(this.textarea, 'keydown', this.operation(this, this.keydown))
}
/**
* 绑定事件
* @param emitter
* @param type
* @param f
*/
on (emitter, type, f) {
if (emitter.addEventListener) {
emitter.addEventListener(type, f, false)
} else if (emitter.attachEvent) {
emitter.attachEvent('on' + type, f)
} else {
let map = emitter._handlers || (emitter._handlers = {})
map[type] = (map[type]).concat(f)
}
}
/**
* 按下按键事件
* @param event
*/
keydown (event) {
let selectionStart = this.textarea.selectionStart
let selectionEnd = this.textarea.selectionEnd
let selected = window.getSelection().toString()
let indent = ' '
if (event.keyCode === 9) { // tab was pressed
event.preventDefault()
selected = indent + selected.replace(/\n/g, '\n' + indent)
this.textarea.value = this.textarea.value.substring(0, selectionStart) + selected + this.textarea.value.substring(selectionEnd)
this.setCursorPosition(selectionStart)
this.textarea.setSelectionRange(selectionStart + indent.length, selectionStart + selected.length)
} else if (event.keyCode === 8) { // backspace
if (this.textarea.value.substring(selectionStart - indent.length, this.textarea.getCaretPosition()) === indent) {
this.textarea.value = this.textarea.value.substring(0, selectionStart - indent.length + 1) + this.textarea.value.substring(selectionEnd)
this.setCursorPosition(selectionStart - indent.length + 1)
}
} else if (event.keyCode === 37) { // left arrow
if (this.textarea.value.substring(selectionStart - indent.length, this.textarea.getCaretPosition()) === indent) {
this.setCursorPosition(selectionStart - indent.length + 1)
}
}
if (event.keyCode === 39) { // right arrow
if (this.textarea.value.substring(selectionStart + indent.length, this.textarea.getCaretPosition()) === indent) {
this.setCursorPosition(selectionStart + indent.length - 1)
}
}
}
/**
* 设置光标位置
* @param position
*/
setCursorPosition = function (position) {
this.textarea.selectionStart = position
this.textarea.selectionEnd = position
this.textarea.focus()
}
operation (that, f) {
return function () {
return f.apply(that, arguments)
}
}
}
JS调用Textarea类
// 导入Textarea类
import {Textarea} from './Textarea.js'
// 调用
let content = document.getElementById('content')
let textarea = new Textarea(content)
textarea.tabIndent()