window.getSelection() 给了我选定的文本,但我想要 HTML [英] window.getSelection() gives me the selected text, but I want the HTML

查看:52
本文介绍了window.getSelection() 给了我选定的文本,但我想要 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展 WYSIWYG HTML 编辑器(适用于 Firefox),我想在选择周围添加标签.我在 Mozilla Midas 规范中找不到实现此目的的函数.

I'm extending a WYSIWYG HTML editor (for Firefox), I want to add tags around a selection. I can't find a function to accomplish this in the Mozilla Midas specification.

有一个命令可以用 HTML 替换选择.
因此,如果我可以阅读选择内容,我可以将我的标签添加到这个字符串中.

There is a command to replace the selection with HTML.
So if I could read the selection contents, I could add my tags to this string.

window.getSelection() 几乎可以工作,但是它给了我 nsISelection 转换为纯文本字符串.

window.getSelection() almost works, but it gives me nsISelection which converts to a plain-text string.

PS:document.getSelection() 返回纯文本字符串,甚至不是 nsISelection.

PS: document.getSelection() returns the plain-text string not even a nsISelection.

推荐答案

查看DOM 范围规范.您可以使用以下命令从 Firefox 中的用户选择中获取 Range:

Take a look at the DOM Range spec. You can get a Range from the user selection in Firefox using:

var range = window.getSelection().getRangeAt(0);

注意一些浏览器,包括火狐,允许多选,可以通过选择的getRangeAt()方法访问.

Note that some browsers, including Firefox, allow multiple selections, which can be accessed via the getRangeAt() method of the selection.

Range 以 DOM 节点和这些节点内的偏移量表示.一旦你有了你的 Range,就不能直接做你想做的事,因为范围的边界可能在 DOM 树的不同级别的不同节点中,所以简单地用一个包围范围的内容标记并不总是可能的.您也许可以执行以下操作,但它会创建一个新的块元素来包含所选内容:

The Range is expressed in terms of DOM nodes and offsets within those nodes. Once you've got your Range, it's not straightforward to do exactly what you want, since the range's boundaries could be in different nodes at different levels of the DOM tree, so simply surrounding the Range's content with a tag is not always possible. You may be able to do something like the following, although it will create a new block element to contain the selected content:

var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var div = document.createElement("div");
div.style.color = "yellow";
div.appendChild(selectionContents);
range.insertNode(div);

另一个,hacky,替代方法是使用 documentexecCommand() 方法来修改选择(例如,通过将其设置为特定颜色),然后使用 document.querySelectorAll 或一些选择器库来选择具有该颜色的元素,然后对其应用样式.

Another, hacky, alternative is to use the execCommand() method of document to modify the selection (e.g. by setting it to a particular colour) and then using document.querySelectorAll or some selector library to select elements with that colour and then apply styling to them.

这篇关于window.getSelection() 给了我选定的文本,但我想要 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆