div editable
by San-Kai Liao
HTML
<div class="editable">
sdfsdf
<br/>
werwer
</div>
CSS
div.editable {
height: 100px;
width: 100px;
border:1px solid #CCC;
}
JavaScript
$('div.editable').resizable().draggable();
$('div.editable').on('dblclick', function (evt) {
var self = $(evt.currentTarget);
var txtbox = $('<textarea/>');
txtbox.css('width', self.width());
txtbox.css('height', self.height());
txtbox.css('left', self.position().left);
txtbox.css('top', self.position().top);
txtbox.css('background', 'white');
txtbox.css('position', 'absolute');
//編輯完成(離開焦點)
txtbox.on('blur', function (evt) {
var input = txtbox.val().replace(/ /g, " ").replace(/\n/g, '<br />');
//清除原始文字內容,並將 /n 轉為 <br/>
self.contents().filter(function (index, el) {
if ($(el)[0].nodeType === 3 || $(el).is('br')) {
$(el).remove();
}
});
self.prepend(input).show();
//從頁面上移除文字輸入框
txtbox.remove();
}).appendTo('body').focus();
//將 <br/> 轉為 /n 後再匯入到 textarea
self.contents().filter(function (index, el) {
//文字部分
if ($(el)[0].nodeType === 3) {
txtbox.append($(el).text());
}
//斷行部分
if ($(el).is('br')) {
txtbox.append("\n");
}
}).hide();
});