开发者

How can we get randomly selected text and image in javascripton on mouseup from page?

开发者 https://www.devze.com 2023-01-13 15:48 出处:网络
I want to get selected text and image on a mouse event.I\'ve tried window.getSelection() but this will return only selected text not images.

I want to get selected text and image on a mouse event. I've tried window.getSelection() but this will return only selected text not images.

Can someone help me understand how I can 开发者_开发技巧get the selected image in JavaScript?


At first I thought this would be a duplicate of this, but then again, the other question doesn't show how to select the nodes from the selection.

window.getSelection() will give you the selection, but not the current (or highlighted) selection. You need to use the selection's getRangeAt method for that

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

which will give you the range object (refer DOM Range) of currently selected item(s). In this Range object, there are startContainer, endContainer, and commonAncestorContainer, which will give you the DOM node of whatever you're selecting. Note that for text, it will mean text nodes, of which its parent might be a p node. If you read the first link, you will know that you can also extract it out of the document, or you can clone the selection and modify it without touching the original.

But if you want to edit-in-place what is in the selection, you may have to traverse through the nodes in the selection by yourself. If the image you select is at the beginning or the end of the selection, it is easy to get it: just use either startContainer or endContainer. But things get tricky when you have image between blocks of text.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号