In an html page you might have some code with two paragraphs like this:
<hr />
<p>The first paragraph</p>
<p>The second paragraph</p>
<hr />
and very simply, these two tags would render like this:
The first paragraph
The second paragraph
What I am interested in is to allow the user to click somewhere in the rendered html code so as to insert a new element with JQuery开发者_StackOverflow中文版. For example if I click between the letter i and the letter r (just a click, no higlighting/selection)in the word f*ir*st found in the first paragraph, I would be able to insert a custom span element or whatever I like exactly in that position in the HTML code resulting in something like this:
<hr />
<p>The fi<span id="myCustomSpan"></span>rst paragraph</p>
<p>The second paragraph</p>
<hr />
Any ideas that can help me? My request excludes absolute positioning. That would not solve my issues.
This is dirty but makes use of contenteditable
: http://jsfiddle.net/Jj9Mp/.
$('div').click(function(e) {
$('div').attr('contenteditable', true);
document.execCommand("InsertHTML", false, "<span class=red>!</span>")
e.stopPropagation();
});
$(':not(div)').click(function(e) {
if($(this).parents('div').length === 0) {
$('div').attr('contenteditable', false);
} else {
$('div').click();
}
e.stopPropagation();
});
Here is my solution : http://jsfiddle.net/gion_13/L6aeT/
It works by calculating the actual size (in px) of the string.
This can be done with somewhat complex scripting.
i can state an algorithm that you can try.
1.JQuery have an API offset() http://api.jquery.com/offset/ using that you can get the offset and element.
2.Now you need to take the innerHTML of the element, take it as string, from the offset Y val, split at position Y in the string. make the element as two elements.
3.Now you can directly create an Element in script using creteElement(tagname) and set the innerHTML and then insert it in between the two elements
精彩评论