2016-12-03 262 views
0

帖下面的代碼設置的基礎上caret值插入符號:如何將插入符號放在contenteditable div中而忽略HTML標籤?

<div ref="editable" contenteditable="true"> 
    This text can be edited by the user. Right away. 
</div> 
<button type="button" @click="setCaret">Set caret</button> 

setCaret() { 
    const node = this.$refs.editable 
    node.focus() 
    const textNode = node.firstChild 
    const caret = node.textContent.search('R') 
    const range = document.createRange() 
    range.setStart(textNode, caret) 
    range.setEnd(textNode, caret) 
    const sel = window.getSelection() 
    sel.removeAllRanges() 
    sel.addRange(range) 
} 

如果你包p標籤內的文本,但:

<p>This text can be edited by the user.</p> 
<p>Right away.</p> 

你得到這個錯誤:

App.vue?6b51:36Uncaught DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset -1.(…) 

如何修改代碼以便setCaret在忽略HTML標籤的同時設置插入符號?

回答

2

您可能需要搜索的DIV裏面遞歸這些節點:

function findTextNode(node) { 
    const childNodes = node.childNodes; 
    if (childNodes.length > 0) { 
    for(let i=0; i<childNodes.length; i++) { 
     const child = childNodes[i]; 
     const result = findTextNode(child); 
     if (result) { 
     return result; 
     } 
    } 
    return false; 
    } else { 
    const place = node.textContent.search('R'); 
    if (!node.tagName && place!==-1) { 
     return node; 
    } 
    return false; 
    } 
} 

工作小提琴這裏:http://jsfiddle.net/1x6knn37/

相關問題