JS inserts content at the cursor position in the Editable div

Source: Internet
Author: User

We will introduce how to insert content at the specified position in the Editable div, just like the editor we are using. Below I will introduce several instances.


First, enable the edit mode for the DIV.

The Code is as follows: Copy code

<Div contenteditable = true id = "divTest"> </div>

Enable the div editing mode by setting contenteditable = true, so that the DIV can input content like the text box.

Don't talk about the topic anymore. The following describes how to obtain or set the cursor position.

2 steps

1: Get the cursor position in the DIV

2: Change the cursor position

The Code is as follows: Copy code


Var cursor = 0; // cursor position
Document. onselectionchange = function (){
Var range = document. selection. createRange ();
Var srcele = range. parentElement (); // get the current element
Var copy = document. body. createTextRange ();
Copy. moveToElementText (srcele );

For (cursor = 0; copy. compareEndPoints ("StartToStart", range) <0; cursor ++ ){
Copy. moveStart ("character", 1); // Changes the cursor position. In fact, we are recording the number of cursor.
}
}

Bind a cursor change event to the document. Used to record the cursor position.

In this way, you can get the cursor position of the DIV.

The Code is as follows: Copy code


Function moveEnd (obj ){

LyTXT1.focus ();
Var r = document. selection. createRange ();
// Because the cursor is automatically moved from the current cursor (as if the text box is counted from 0 .) so we need to get the current cursor position, and then we can calculate the number of digits to move, so that we can move the cursor to the desired position.
R. moveStart ('character ', lyTXT1.innerText. length-cursor );
R. collapse (true );
R. select ();
}

Through the above, we can move the cursor in the DIV to the end.

A complete instance

The Code is as follows: Copy code

<Button type = "button" onclick = "document. getElementById ('test '). focus (); insertHtmlAtCaret ('<B> INSERTED </B>'); "> insert character </button>
<Div contentEditable = "true" style = "height: 50px; border: 2px solid red;" id = "test"> & nbsp; </div>

 

Function insertHtmlAtCaret (html ){
Var sel, range;
If (window. getSelection ){
// IE9 and non-IE
Sel = window. getSelection ();
If (sel. getRangeAt & sel. rangeCount ){
Range = sel. getRangeAt (0 );
Range. deleteContents ();

// Range. createContextualFragment () wocould be useful here but is
// Non-standard and not supported in all browsers (IE9, for one)
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 );

// Preserve the selection
If (lastNode ){
Range = range. cloneRange ();
Range. setStartAfter (lastNode );
Range. collapse (true );
Sel. removeAllRanges ();
Sel. addRange (range );
}
}
} Else if (document. selection & document. selection. type! = "Control "){
// IE <9
Document. selection. createRange (). pasteHTML (html );
}
}


Let's look at a jquery-based instance.

The Code is as follows: Copy code

<! Doctype html public "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type">
<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
<Title> contenteditable </title>
<Style>
*{
Margin: 0; padding: 0;
}
. Im-message-area {
Width: 98%;
Padding: 2px;
Height: 75px;
Border: #000 solid 1px;
Background: # fff;
Font: 12px/20px arial, "5b8b4f53 ";
Word-wrap: break-word;
Overflow-y: auto;
Line-height: 1;
}
. Ul {display: none ;}
. Ul li {
Background-color: # CCC;
Width: 50px;
}
</Style>
<Script language = "javascript" type = "text/javascript">
Function inimage (text ){
Var obj = $ (". im-message-area") [0];
Var range, node;
If (! Obj. hasfocus ){
Obj. focus ();
}
If (window. getSelection & window. getSelection (). getRangeAt ){
Range = window. getSelection (). getRangeAt (0 );
Range. collapse (false );
Node = range. createContextualFragment (text );
Var c = node. lastChild;
Range. insertNode (node );
If (c ){
Range. setEndAfter (c );
Range. setStartAfter (c)
}
Var j = window. getSelection ();
J. removeAllRanges ();
J. addRange (range );

} Else if (document. selection & document. selection. createRange ){
Document. selection. createRange (). pasteHTML (text );
}
}
$ (Document). ready (function (){
$ ('# Click'). click (function (){
$ ('. Ul'). show ();
})
$ ('. Ul li'). each (function (){
$ (This). click (function (){
Inimage ($ (this). text ());
})
})
});
</Script>
</Head>
<Body>
<Div contenteditable = "true" id = "im_message_area" class = "im-message-area"> <br> </div>
<A href = "javascript: void (0)" id = "button"> button </a>
<Ul class = "ul">
<Li> (Laugh) </li>
<Li> (CRY) </li>
<Li> (LE) </li>
</Ul>
</Body>
</Html>

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.