I have a text in my markup:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum condimentum consectetur tellus, at bibendum felis ultrices eu.
Nullam nibh urna, euismod a blandit ut, fermentum a leo. Maecenas pharetra elementum fringilla.
Quisque condimentum, nibh quis elementum porttitor, magna libero malesuada dolor, ut feugiat tortor lectus ac turpis. Integer tristique molestie enim, sit amet commodo risus tempus non.
When user selects a text and presses CTRL+Enter I want to wrap the selected text with tags. I got to getting the selected text, but cannot find how I can wrap it with the markup. Here is what I have:
function getSelectedText () {
if (window.getSelection) {
return window.getSelection ().toString ();
}
else {
if (document.selection) {
return document.selection.createRange ().text;
}
}
return '';
}
$ (document).ready (function() {
// User pressed a key
$ (document).keydown (function(e) {
// is it CTRL+ENTER?
if (e.which == 13 && e.ctrlKey) {
alert('You have selected ' + getSelectedText ());
// now I need to highlight the text I got
// ????
}
});
});
Please note! A simple find/replace does not do, if a user selected a single 'a' letter which can be found 10 times in the text, I want to highlight the only 'a' he selected. I've studied range objects, but can't figure out how to achieve it, help me out, please.
Please see demo at jsfiddle.
解决方案
one of the examples is exactly what you're after.