JS to specify the focus difference in the text box value

Source: Internet
Author: User
Tags button type

Reference article: http://www.111cn.net/wy/js-ajax/52270.htm


This method is feasible.

With the above we can move the cursor in the div to the last face.

A complete example

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 () would be useful
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);
}
}



This article from "Jianbo" blog, reproduced please contact the author!

JS to specify the focus difference in the text box value

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.