// Suppose that we know the id of the necessary textarea tag
var Textarea = document.getElementById (textarea_id);
var Container = document.createElement ("DIV");
// Add the container to the parent of the Textile, then move it inside the container and hide it
Textarea.parentNode.insertBefore (Container, Textarea);
Container.appendChild (Textarea);
Textarea.style.display = 'none';
// Create a frame and add it to the editor container
var iframe = "<iframe style = 'width: 100%; height: 100%;' src = \ "javascript: document.open (); document.domain = '"+
document.domain + "'; document.close (); \" frameborder =' 0 '> </ iframe> ";
Container.innerHTML = iframe + Container.innerHTML;
var Frame = Container.childNodes [0];
// The sly definition of IE;)
var isIE = / * @ cc_on! @ * / false;
// Select the frame document into a separate variable
var FrameDoc = isIE? Frame.contentWindow.document: Frame.contentDocument;
FrameDoc.open ();
// If the content of the body tag is empty, in FF the cursor will become somehow too small.
// To avoid this, add & nbsp; (without space)
FrameDoc.write ('<html> <head> </ head> <body>' + Textarea.value + '& nbsp; </ body> </ html>');
FrameDoc.close ();
FrameDoc.designMode = "on";
FrameDoc.execCommand ("Strikethrough", false, ''); // If IE does not set the focus on the window of the edited frame,
// then in the future it can insert the code at the top of your page, and not into the frame;)
Frame.contentWindow.focus ();
var SelectionRange = isIE? FrameDoc.selection.createRange (): Frame.contentWindow.getSelection (). GetRangeAt (0);
// insert image
var html = "<img src = 'mypicture.gif' />";
if (isIE) {
// everything is simple
SelectionRange.pasteHTML (html);
} else {
// for the rest we use an auxiliary tag
SelectionRange.deleteContents ();
var el = document.createElement ("SPAN");
FrameDoc.getElementsByTagName ("BODY") [0] .appendChild (el);
// Firefox will not understand if you immediately replace outerHTML. In versions below the 3rd such property is absent.
el.innerHTML = html;
SelectionRange.insertNode (el);
el.outerHTML = html;
}
Source: https://habr.com/ru/post/38077/
All Articles