2012-06-20 33 views
6

Làm cách nào để chia một nút/phần tử ở vị trí (lựa chọn).Nút tách Rangy (JS/jQuery)

Ví dụ tôi có dấu sau:

<p>This is <a href="">a te|st</a>, you like?</p> 

(ống này đại diện cho vị trí/lựa chọn)

Tôi muốn chuyển nó sang:

<p>This is <a href="">a te</a></p>|<p><a href="">st</a>, you like?</p> 

Duy trì sự lựa chọn.

Bất kỳ ý tưởng nào?

Tôi và sử dụng thư viện Rangy cũng như jQuery nhưng có thể sử dụng JS thô nếu có.

Trả lời

10

Bạn có thể thực hiện việc này bằng cách tạo phạm vi mở rộng từ dấu mũ tới điểm ngay sau đoạn văn và sử dụng phương pháp extractContents() của nó.

Live Demo: http://jsfiddle.net/timdown/rr9qs/2/

Code:

var sel = rangy.getSelection(); 
if (sel.rangeCount > 0) { 
    // Create a copy of the selection range to work with 
    var range = sel.getRangeAt(0).cloneRange(); 

    // Get the containing paragraph 
    var p = range.commonAncestorContainer; 
    while (p && (p.nodeType != 1 || p.tagName != "P")) { 
     p = p.parentNode; 
    } 

    if (p) { 
     // Place the end of the range after the paragraph 
     range.setEndAfter(p); 

     // Extract the contents of the paragraph after the caret into a fragment 
     var contentAfterRangeStart = range.extractContents(); 

     // Collapse the range immediately after the paragraph 
     range.collapseAfter(p); 

     // Insert the content 
     range.insertNode(contentAfterRangeStart); 

     // Move the caret to the insertion point 
     range.collapseAfter(p); 
     sel.setSingleRange(range); 
    } 
}