Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

javascript - window.getSelection() gives me the selected text, but I want the HTML

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...