window.getSelection()给我所选的文本,但是我想要HTML [英] window.getSelection() gives me the selected text, but I want the HTML
问题描述
有一个命令用HTML替换选择。
所以如果我可以阅读选择内容,我可以添加我的标签到这个字符串。
window.getSelection()
几乎可以工作,但它给了我 nsISelection
,转换为纯文本字符串。
PS: code> document.getSelection()返回纯文本字符串甚至不是 nsISelection
。
看看 DOM Range spec 。您可以从Firefox中的用户选择中获取 Range
:
var range = window.getSelection()。getRangeAt(0);
请注意,某些浏览器(包括Firefox)允许多个选择,可以通过 getRangeAt()
选择方法。
范围
在DOM节点和这些节点内的偏移量。一旦你有你的范围
,就不太容易做到你想要的,因为范围的边界可以在DOM树的不同级别的不同节点,所以简单使用标签围绕范围的内容并不总是可能的。您可能可以执行以下操作,尽管它将创建一个新的块元素来包含所选内容:
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,另一种是使用 execCommand()
方法文档
修改选择(例如通过将其设置为特定颜色),然后使用 document.querySelectorAll
或某些选择器库来选择具有该颜色的元素,然后将样式应用于它们。
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.
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()
almost works, but it gives me nsISelection
which converts to a plain-text string.
PS: document.getSelection()
returns the plain-text string not even a nsISelection
.
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);
Note that some browsers, including Firefox, allow multiple selections, which can be accessed via the getRangeAt()
method of the selection.
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);
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屋!