做一個「雙擊文字就變成輸入框,按 Tab 或點別處就存回」的小功能。這是常見的行內編輯(inline editing)互動,用原生 JS 就能完成。
<div class="img_1" id="img_1">
<input type="image" class="img_1" src="img/cump.png">
<div class="noteText" id="noteTxt" ondblclick="changeName(this.id);">123</div>
</div>
function changeName(noteTxtId) {
var noteTxt = document.getElementById(noteTxtId);
noteTxt.style.display = "none";
var div = noteTxt.parentNode;
if (!document.getElementById("noteInput")) {
var text = document.createElement("input");
text.type = "text";
text.id = "noteInput";
// 讓輸入框的外觀盡量與原本的 div 一致
text.style.width = getStyle(noteTxt, 'width');
text.style.height = getStyle(noteTxt, 'height');
text.style.marginTop = getStyle(noteTxt, 'marginTop');
text.style.textAlign = getStyle(noteTxt, 'textAlign');
text.value = noteTxt.innerHTML;
div.appendChild(text);
text.select();
// 失焦時把值寫回 div,並移除輸入框
text.onblur = function () {
noteTxt.style.display = "block";
noteTxt.innerHTML = text.value;
div.removeChild(text);
};
}
}
// 取得 CSS 樣式(跨瀏覽器)
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr]; // IE
} else {
return getComputedStyle(obj, false)[attr]; // 標準瀏覽器
}
}
.img_1 {
width: 80px;
height: 70px;
position: absolute;
}
.noteText {
width: 80px;
height: 15px;
text-align: center;
margin-top: 70px;
word-break: break-all;
}
整個互動的骨架是「隱藏 div → 動態插入 input → 失焦時寫回並移除 input」。用 getComputedStyle 讀取原元素的寬高與對齊方式,是為了讓切換瞬間不產生版面跳動。
有幾個地方可以再強化:一是加上 input 已存在的檢查,避免連續雙擊產生多個輸入框;二是失焦時若使用者按 Esc 應該取消編輯而不是存檔;三是寫回時最好用 textContent 而非 innerHTML,否則使用者輸入的內容若含標籤會被當成 HTML 解析,形成 XSS 風險。