Insert text in Javascript contenteditable div

后端 未结 4 1682
别跟我提以往
别跟我提以往 2020-12-29 12:24

I have a problem where I need to insert a text (string, may or may not have html tags) to a div. It has to be a div and not a textarea.

Is there anyway to do that? F

4条回答
  •  暖寄归人
    2020-12-29 13:12

    You can also use a round-about method using insertImage. You insert a fake image (or a small one) using the execCommand "insertImage", then you use Javascript to replace the innerHTML to add the text.

    For example:

    iFrame.focus()
    iFrame.document.execCommand("insertImage", "", "fakeimage.jpg")
    iFrame.document.body.innerHTML=iFrame.document.body.innerHTML.replace("", "MY CUSTOM HTML HERE!")
    

    Whereas iFrame is equal to the id of the intended iFrame. Or, you could use a DIV layer by using document.getElementById("IDofDIVlayer").innerHTML

    Be sure to focus before calling the execCommand, otherwise it may not work in IE.

    This method works in IE too. Tested.

提交回复
热议问题