How to insert text or images in an editable div

Source: Internet
Author: User

Recently, someone asked me a question on the internet, inserting text or images in the Editable div. I have never used the web online editor and will not study the source code. Later, this function was also used in an online chat web project. I took a special look at the code.
Basically, the editor or online chat web page is unlikely to be used as an input box in textarea, because we may need to insert images or hyperlinks, therefore, it is required to select iframe or div as the input box.
I use div here.
To make the div editable, you must add the contentEditable = "true" attribute.
Then, you can obtain the cursor position (or select the text position) for text or html insertion.
Because Firefox and other standard browsers support the getSelection method, IE9 and above are also supported, but the evil iE6-8 is not supported, so it should be written in two parts of the Code. Because these codes are simple, I will post them first.
[Javascript]
Function insertHTML (html)
{
Var dthis = $ ("# div3") [0]; // a div of the content to be inserted. This statement is not required in the standard browser.
Var sel, range;
If (window. getSelection)
{
// IE9 and non-IE
Sel = window. getSelection ();
If (sel. getRangeAt & sel. rangeCount ){
Range = sel. getRangeAt (0 );
Range. deleteContents ();
Var el = document. createElement ('div ');
El. innerHTML = html;
Var frag = document. createDocumentFragment (), node, lastNode;
While (node = el. firstChild ))
{
LastNode = frag. appendChild (node );
}

Range. insertNode (frag );
If (lastNode ){
Range = range. cloneRange ();
Range. setStartAfter (lastNode );
Range. collapse (true );
Sel. removeAllRanges ();
Sel. addRange (range );
}
}
}
Else if (document. selection & document. selection. type! = 'Control ')
{

$ (Dthis). focus (); // in a non-standard browser, you must first Insert the html div to get the focus.
Ierange = document. selection. createRange (); // obtain the cursor position
Ierange. pasteHTML (html); // insert html at the cursor position. If only text is inserted, fus. text = "..."
$ (Dthis). focus ();

}
}
The above code basically completes inserting the specified html content in the Editable div. The code can be found everywhere in baidu or google, so I will not explain why it is so common)

After execution, it will be found that it is normal in IE or non-standard browsers. It is not normal in Firefox or chrome.

For example, on the following page, I have an indefinite number of divs (which may be generated dynamically by a program). I only need one of the divs to insert html.
[Html]
Other html elements .....
<Div id = "div1" contentEditable = "true"> </div>
 
<Div id = "div2" contentEditable = "true"> </div>
 
<Div contentEditable = "true" id = "div3"> </div>
<Input type = "button" id = "cmdInsert" onclick = "execute the insert html method to div3"/>
<Pre name = "code" class = "html"> ...... other html elements ...... </pre> <br>
<P> </p>
<Pre> </pre>
<Br>
On the above page, I only need div3 to support html insertion. The other two are only editable. <Br>
<P> </p>
<P> when you use the above Code, you will find that if div3 is the last one that loses focus, everything is normal. If it is not div3 or I click another control or blank space on the page, we will find that the inserted html is not inserted into the desired div3, but is inserted elsewhere. </P>
<P> This is not a bug, but a normal phenomenon. getSelection can span many fields, so it cannot be guaranteed that the obtained range must be the div you need. <br>
</P>
<P> here I declare again that I really don't want to see (even if I have a look) How the online web editor in China is implemented. I have reviewed du Niang and google and found a solution. </P>
<P> <br>
</P>
<P> In fact, what we need to solve is one thing. When the elements on the page (including div or any element) lose the focus, we only need to obtain whether the last div3 div with no focus is div3. If yes, execute the above Code. If not, add the html to be inserted directly after the div3 content (hard encoding is required. Don't tell me no) </p>
<P> at the beginning, I thought of setting a click event and focus event for div3. When the mouse clicks in or gets the focus, I set a variable such as isdiv3 to true, set it to false elsewhere (this method does not actually work. Here I will not explain why it does not work. There are various situations that can lead to a focus, isdiv3 is still not set to true, and an event needs to be set for each html element to make isdiv3 false, which is a terrible thing ). </p>
<P> <br>
</P>
<P> here I release a common solution that is not easily disturbed. </P>
<P> write at the top of the page </p>
<P> <style> </p>
<P> div: focus {z-index: 100;} // you can set the value at Will here. 100 is just a column. <br>
</P>
<P> </style> </p>
<P> the style above tells us that when only the div gets the focus, it will generate a css attribute, that is, z-index is set to 100, the css attribute, which loses focus in any form, is gone. You can also set other css attributes. Because div3 also loses focus when we click the button to execute the function (getSelection still exists) </p>
<P> <br>
</P>
<P> the following idea is clear: let's write another function. </p>
<P> </p> <pre name = "code" class = "javascript"> var lastFocusID = "";
Function getFocus ()
{
Var divlist = document. getElementsByTagName ('div ');
For (var I = 0; I <divlist. length; I ++)
{
Var ta = divlist. item (I );
If (window. getComputedStyle (ta, null). zIndex! = Null & window. getComputedStyle (ta, null). zIndex = 100 ){
If (ta. id & ta. id! = Null)
LastFocusID = ta. id. toString ();
Else
LastFocusID = "";
Break;
}
Else
LastFocusID = "";
}

}
// Add another full screen event
<Pre name = "code" class = "javascript"> $ (window). click (function (e)
{
If (window. getSelection)
{
Var getevent = e. srcElement? E. srcElement: e.tar get; // do not tell me what this sentence means

If (getevent. tagName = "INPUT" & getevent. id! = Null & getevent. id = "cmdInsert ")
{
// Indicates the html insertion button.
// The getFocus method is not executed.
}
Else
GetFocus (); // unless you click the button that inserts html, you must execute getFocus to update the div that loses the focus.
}


}) </Pre> <br>
<Br>
<P> </p>
<Pre> </pre>
<Br>
Then modify the insertHTML method <pre name = "code" class = "javascript"> function insertHTML (html)
{
Var dthis = $ ("# div3") [0];
Var sel, range;
If (window. getSelection)
{
If (lastFocusID! = "Div3 ")
{Www.2cto.com
<Pre name = "code" class = "javascript"> $ ("nvidiv32.16.html (dthis. innerHTML + html); // indicates that the user may focus on other controls or perform other operations. </pre> return; // no execution is performed later. <br>
} <Br>
<Br>
.......... // Other codes are the same as before <br>
<Pre> </pre>
<Br>
In this way, contents may be inserted randomly in Firefox or chrome.
<P> </p>
<P> <br>
</P>
<P> of course, this is just an idea. You are welcome to provide better methods and better performance ideas. <Br>
</P>
<P> <br>
</P>
 
</Pre>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.