[英]Wrap highlighted text within textarea with strong tags using javascript/jquery
I am looking to create a javascript/jquery function to wrap a piece of highlighted text from a textarea in strong tags - similar to the WYSIWYG editor here. 我正在寻找创建javascript / jquery函数,以将文本区域中的突出显示的文本包裹在强标签中-类似于此处的WYSIWYG编辑器。
Is this possible and if so can you point me in the right direction. 这是可能的,如果可以,您可以指出正确的方向。
EDIT: 编辑:
OK so here's a hopefully clearer description of what I want... 好的,这是希望的更清晰的描述...
I have a textbox on my page which I can type in. 我的页面上有一个文本框可以输入。
I then want to be able to highlight a part of this text and wrap the highlighted part in <strong>
tags 然后,我希望能够突出显示此文本的一部分并将突出显示的部分包装在
<strong>
标记中
So if the text box had the words one two three
and I highlighted the word "two", I want to be able to wrap that word in the strong tags - so becoming one <strong>two</strong> three
因此,如果在文本框中有词
one two three
,我强调这个词“二”,我希望能够包裹在强烈的标记,字-所以成为one <strong>two</strong> three
Hope this is clearer... I know there are plugins out there but I don't need the full WYSIWYG functionality. 希望这更清楚...我知道那里有插件,但是我不需要完整的所见即所得功能。
My Rangy inputs (terrible name, I know) jQuery plug-in does this. 我的Rangy输入 (我知道这个名字很糟糕)是jQuery插件。
Example code: 示例代码:
$("#foo").surroundSelectedText("<strong>", "</strong>");
jsFiddle: http://jsfiddle.net/aGJDa/ jsFiddle: http : //jsfiddle.net/aGJDa/
I love Rangy! 我爱兰吉! Use it often!
经常使用它! But I didn't want to include the whole thing just for this little application, so I did it using document.execCommand to wrap the selected text, then used the href (third parameter of the CreateLink execCommand) to find the element, wrap it with what I wanted, and then remove the link:
但是我不想只包含这个小应用程序的全部内容,因此我使用document.execCommand来包装所选文本,然后使用href(CreateLink execCommand的第三个参数)来查找元素并将其包装用我想要的内容,然后删除链接:
document.execCommand('CreateLink', false, 'uniqueid');
var sel = $('a[href="uniqueid"]');
sel.wrap('<strong />')
sel.contents().unwrap();
document.execCommand is supported by all major browsers so you should be safe hacking it this way. 所有主要浏览器都支持document.execCommand,因此您应该安全地以这种方式对其进行破解。 In the browsers I've tested, the browser itself will close and open tags for you, so if you're selecting from the middle of one html tag to the middle of another, it should nest the tags correctly.
在我测试过的浏览器中,浏览器本身会为您关闭和打开标签,因此,如果您从一个html标签的中间选择另一个,则应该正确地嵌套标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.