jquery 實現可編輯div



html大致例如以下:

<ol id="ol_group" class="list-group list_of_items">
    <li class="list-group-item completed_item">
        <div class="text_holder">
            how are you?
            <div class="btn-group pull-right">
                <button class="delete btn btn-warning">Delete</button>
                <button class="edit btn btn-success">Edit</button>
            </div>
        </div>
        <div class="checkbox">
            <label>
                <input type="checkbox" class="pull-right">
            </label>
        </div>
    </li>
</ol>
(這僅僅是一部分,但演示效果夠了)


在js文件給 Eidtbutton加入事件並實現.test-holder的div的可編輯化:

body.on('click', '.text_holder .btn-group .edit', function(){
    var divedit = $(this).parent().parent();
    if (!divedit){
        return;
    }
    if (divedit.children("input").length > 0) {
        return;
    }
    var mtext = divedit.text().substring(0, divedit.text().length-10);

    var inputIns = $("<input type='text'/>");  //創建input 輸入框
    var oldtext = divedit.html();        //保存原有的值
    inputIns.width(divedit.width()/3*2); //設置INPUT與DIV寬度一致
    inputIns.val(mtext);
    divedit.html(""); //刪除原來單元格DIV內容
    inputIns.appendTo(divedit).focus().select(); //將須要插入的輸入框代碼插入DOM節點中
    inputIns.click(function () {
        return false;
    });
    //處理回車和ESC事件
    inputIns.keyup(function (event) {
        var keycode = event.which;
        if (keycode == 13) {
            var newText = oldtext.replace(mtext, $(this).val());
            divedit.html(newText);         //設置新值
        }
        if (keycode == 27) {
            divedit.html(oldtext);         //返回舊值
        }
    }).blur( function (event) {
            if($(this).val() != oldtext){
                var newText = oldtext.replace(mtext, $(this).val());
                divedit.html(newText);         //設置新值
            }else{
                divedit.html(oldtext);
            }
        }
    );
});

效果圖:



參考資料:

http://blog.csdn.net/billhepeng/article/details/7409125




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM