换了种方式,勉强算实现了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
td input{
font-size: 16px;
}
</style>
</head>
<body>
<table border="1">
<tr>
<th width="100">学科</th>
<th width="400">说明</th>
</tr>
<tr>
<td>Java</td>
<td>何以解忧,唯有Java</td>
</tr>
<tr>
<td>Python</td>
<td>人生苦短,要学Python</td>
</tr>
<tr>
<td>PHP</td>
<td>PHP是世界上最好的编程语言</td>
</tr>
</table>
<script>
tdObj = document.getElementsByTagName('td');
var content = '';
for (let i in tdObj) {
tdObj[i].onclick = function (e) {
content = this.innerText;
var inputObj = document.createElement('input');
inputObj.name = 'temp'; //好像不加name也没什么问题
inputObj.value = content;
inputObj.style.width = '100%';
inputObj.style.height = '100%';
inputObj.style.border = 'none';
inputObj.style.outline = 'none';
this.innerHTML = '';
this.append(inputObj);
inputObj.focus();
inputObj.onclick = function (e) {
e.stopPropagation(); //防止input冒泡
}
inputObj.oninput = function (e) {
content = inputObj.value; //更新临时内容
}
inputObj.onblur = function (e) {
this.parentNode.innerHTML = content; //更改父节点内容
}
inputObj.onkeydown = function (e) {
if (e.code === 'Enter') { //想用keyCode == 13 貌似不建议用了
this.parentNode.innerHTML = content;
}
}
}
}
</script>
</body>
</html>