contenteditable可編輯區(qū)域設(shè)置換行實現(xiàn)技巧實例
contenteditable 在需要自定義插入換行符 br
1.方式一,添加換行符 br 進行換行
其中在末尾換行時需要增加兩個br,如不增加則第一次不會產(chǎn)生換行
<div class="inputContent scroll" contenteditable="true" @keydown="inputContent_keydown" ></div>
function inputContent_keydown(e) {
// 1.快捷鍵判斷 回車加ctrl
if( e.keyCode==13 && e.ctrlKey) {
if (document.selection) {//IE9以下
document.selection.createRange().pasteHTML(content);
} else {
let doc_fragment = document.createDocumentFragment();
// 創(chuàng)建br
let new_ele = document.createElement('br');
doc_fragment.appendChild(new_ele);
// 獲取當(dāng)前選擇
let range = window.getSelection().getRangeAt(0);
range.deleteContents();
// 判斷是否是最后一個元素如果是多加一個
if (!hasNextSibling(range.endContainer) && range.startOffset == range.startContainer.length) {
let extra_break = document.createElement('br');
doc_fragment.appendChild(extra_break);
}
range.insertNode(doc_fragment);
//創(chuàng)建新范圍
range = document.createRange();
range.setStartAfter(new_ele);
range.collapse(true);
//插入
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}
function hasNextSibling(node) {
if (node.nextElementSibling) {
return true;
}
while (node.nextSibling) {
node = node.nextSibling;
if (node.length > 0) {
return true;
}
}
return false;
}2.方式二,使用 document.execCommand
(已廢棄,但大部分瀏覽器仍然支持)document.execCommand('insertLineBreak')
以上就是contenteditable 可編輯區(qū)域設(shè)置換行的詳細內(nèi)容,更多關(guān)于contenteditable 可編輯區(qū)域設(shè)置換行的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
javascript 文本框水印/占位符(watermark/placeholder)實現(xiàn)方法
html5為表單元素(type為text/password/search/url/telephone/email)新增了一個placeholder屬性,為輸入框提供一種提示2012-01-01
從jQuery.camelCase()學(xué)習(xí)string.replace() 函數(shù)學(xué)習(xí)
camelCase函數(shù)的功能就是將形如background-color轉(zhuǎn)化為駝峰表示法:backgroundColor。2011-09-09
javascript設(shè)計模式之中介者模式學(xué)習(xí)筆記
這篇文章主要為大家詳細介紹了javascript設(shè)計模式之中介者模式學(xué)習(xí)筆記,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
JS提示:Uncaught SyntaxError: Unexpected token ILLEGAL錯誤的解決方法
這篇文章主要介紹了JS提示:Uncaught SyntaxError: Unexpected token ILLEGAL錯誤的解決方法,涉及針對字符串參數(shù)的處理方法,需要的朋友可以參考下2016-08-08
在JavaScript中實現(xiàn)保留兩位小數(shù)的方法小結(jié)
在JavaScript中,處理數(shù)字并格式化它們以顯示特定的小數(shù)位數(shù)是一個常見的需求,特別是,當(dāng)你需要顯示貨幣、測量值或其他需要精確到兩位小數(shù)的數(shù)據(jù)時,本文將詳細介紹幾種在JavaScript中實現(xiàn)保留兩位小數(shù)的方法,需要的朋友可以參考下2024-11-11
用html+css+js實現(xiàn)的一個簡單的圖片切換特效
這篇文章主要介紹了用html+css+js實現(xiàn)的一個簡單的圖片切換特效,需要的朋友可以參考下2014-05-05

