通过JS实现单击div编辑文本内容back

发布于 2021-11-30  3.67k 次阅读  共 785 字


演示

单击我进行编辑

body部分

<div onclick="edit(this)">单击我进行编辑</div>

JS

var titleEditing = false

function edit(element) {
	console.log(titleEditing)
	if (titleEditing) {
		return
	}
	titleEditing = true
	old = element.innerHTML
	element.innerHTML = ""
	var newObj = document.createElement("textarea")
	newObj.className = "textArea"
	newObj.innerHTML = old
	element.append(newObj)
	newObj.focus()
	newObj.onblur = function() {
		element.innerHTML = this.value ? this.value : old
		titleEditing = false
	}
}