[英]Make selected text bold using javascript
I have a text in my markup: 我的标记中有文字:
<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>
When user selects a text and presses CTRL+Enter I want to wrap the selected text with <b></b>
tags. 当用户选择文本并按CTRL + Enter时,我想用<b></b>
标签包裹所选文本。 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. 一个简单的查找/替换操作不起作用,如果用户选择了一个“ a”字母(可以在文本中找到10次),我想突出显示他选择的唯一“ a”字母。 I've studied range objects, but can't figure out how to achieve it, help me out, please. 我已经研究了范围对象,但不知道如何实现它,请帮帮我。
Perhaps this can help you: http://code.google.com/p/rangy/ 也许这可以帮助您: http : //code.google.com/p/rangy/
one of the examples is exactly what you're after. 示例之一正是您所追求的。
You could use document.execCommand()
for this. 您可以为此使用document.execCommand()
。 Here's my answer to a similar question: Javascript: how to un-surroundContents range 这是我对类似问题的回答: Javascript:如何取消周围的内容范围
This works (in Chrome), but so long as it's only called once! 这可以使用(在Chrome中),但是只要调用一次即可!
(running code at http://jsfiddle.net/HaD6k/ ) (在http://jsfiddle.net/HaD6k/上运行代码)
$(document).keypress(function(e) {
if (e.which == 13 && e.ctrlKey) {
var s = getSelection();
var i = s.baseOffset;
var j = s.extentOffset;
var t = $('div').text();
var t0 = t.substring(0, i) + '<span class="b">' +
t.substring(i, j) + '</span>' +
t.substring(j);
$('div').html(t0);
}
});
The reason it only works once is because it modifies the DOM to add the tags, which means next time around the selection offsets and elements aren't contiguous. 它只能运行一次的原因是因为它修改了DOM来添加标签,这意味着下次选择偏移量和元素不连续。 I'm still looking at that... 我还在看...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.