Insert an HTML element in a contentEditable element

前端 未结 2 891
我在风中等你
我在风中等你 2021-02-03 14:57

I have a contentEditable div where I want to insert HTML tags (a simple span element).

Is there a cross browser solution that allows me to insert those tags over my div

2条回答
  •  不知归路
    2021-02-03 15:18

    Here is a kickstart

    // get the selection range (or cursor     position)
    var range = window.getSelection().getRangeAt(0); 
    // create a span
    var newElement = document.createElement('span');
    newElement.id = 'myId';
    newElement.innerHTML = 'Hello World!';
    
    // if the range is in #myDiv ;)
    if(range.startContainer.parentNode.id==='myDiv') {
       // delete whatever is on the range
       range.deleteContents();
       // place your span
       range.insertNode(newElement);
    }
    

    I don't have IE but works fine on firefox, chrome and safari. Maybe you want to play with range.startContainer to proceed only if the selection is made on the contentEditable div.

    EDIT: According to quirksmode range intro you have to change the window.getSelection() part to be IE compatible.

    var userSelection;
    if (window.getSelection) {
        userSelection = window.getSelection();
    }
    else if (document.selection) { // should come last; Opera!
        userSelection = document.selection.createRange();
    }
    

提交回复
热议问题