使用javascript将所选文字设为粗体 [英] Make selected text bold using javascript
问题描述
我的标记中有文字:
<div>
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.
</div>
当用户选择文本并按CTRL + Enter时,我想用<b></b>
标签包裹所选文本.我必须获取选定的文本,但是找不到如何用标记将其包装起来.这是我所拥有的:
When user selects a text and presses CTRL+Enter I want to wrap the selected text with <b></b>
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
// ????
}
});
});
请注意!!简单的查找/替换操作不起作用,如果用户选择了单个"a"字母(可以在文本中找到10次),我想突出显示唯一的"a"字母他选择了.我已经研究了范围对象,但不知道如何实现它,请帮帮我.
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.
请访问 jsfiddle 观看演示.
推荐答案
也许这可以为您提供帮助: http ://code.google.com/p/rangy/
Perhaps this can help you: http://code.google.com/p/rangy/
示例之一就是您所追求的.
one of the examples is exactly what you're after.
这篇关于使用javascript将所选文字设为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!