DIV CSS 佈局教程網

以 JS 為 div 節點實作行內名稱編輯功能
編輯:關於JavaScript     

這篇記錄如何用 JavaScript 讓一個 div 上的文字變成可編輯狀態:雙擊進入編輯、失焦完成儲存。整體思路是「暫時換成 input,用完再換回 div」。

節點的 HTML

<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";

        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();

        text.onblur = function () {
            noteTxt.style.display = "block";
            noteTxt.innerHTML = text.value;
            div.removeChild(text);
        };
    }
}

// 取得樣式表裡定義的樣式值
function getStyle(obj, attr) {
    if (obj.currentStyle) {
        return obj.currentStyle[attr];              // IE
    } else {
        return getComputedStyle(obj, false)[attr];  // Firefox 等標準瀏覽器
    }
}

對應的 CSS

.img_1 {
    width: 80px;
    height: 70px;
    position: absolute;
}

.noteText {
    width: 80px;
    height: 15px;
    text-align: center;
    margin-top: 70px;
    word-break: break-all;
}

補充:用 contenteditable 會更省事

上面這種「換標籤」的做法觀念清楚,但程式碼偏多。HTML5 之後有個更直接的選擇——contenteditable:

<div class="noteText" contenteditable="true" onblur="this.innerHTML = this.textContent">123</div>

加上這個屬性,瀏覽器會原生處理游標、選取、復原等所有編輯行為,你只需要在 blur 或按下 Enter 時把值取走即可,省下大量樣式對齊的工你就會少掉一堆手工對齊的細節。若還想進一步支援 Tab 移動、Esc 取消、以及伺服器端儲存,可以再搭配 blur 事件觸發 Ajax 請求。

無論採用哪一種,都別忘了輸出時使用 textContent 或做適當的轉義,避免使用者輸入的內容被當成 HTML 執行。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved