问题描述
以下是一个 javaScript
函数,用于从 iframe中获取所选内容
Following is a javaScript
function to get selected content from an iframe
function getIframeSelectionText(iframe) {
var win = iframe.contentWindow;
var doc = win.document;
if (win.getSelection) {
return win.getSelection();
} else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange();
}
}
示例 iframe
看起来像这样:
<iframe id="iframeId" type="html" src="__FILE_PATH__" width="100%" height="750px;"></iframe>
实现如下:
var content = getIframeSelectionText(document.getElementById("iframeId"));
我得到的是所选文字。我需要 HTML
(因为我也想抓住图片)
What I get is the text selected. I need HTML
(because I want to catch the images too)
我尝试添加 .html()
到 getSelection()
但是没有用。
解决方案也可能涉及 jQuery
。
I tried adding .html()
to getSelection()
but didn't work.Solution can involve jQuery
too.
如何前进?
---编辑---
此处有一个紧密的提示:
A close hint is found here: window.getSelection() gives me the selected text, but I want the HTML
此处对 Selection
对象的引用如下:
A reference to the Selection
object in question is here: https://developer.mozilla.org/en-US/docs/Web/API/Selection
---可能的解决方案---
这里是我面临的类似(不一样)问题的解决方案:
和另一个
Here is a solution to the similar(not the same) problem I'm facing: https://stackoverflow.com/a/124929/2284357and another one is Get Selected HTML in browser via Javascript
推荐答案
这将返回选定的文本节点
This returns the selected text node
let node = iframe.contentWindow.getSelection().baseNode
之后可用于获取父节点HTML
which afterwards can be used to get the parent node HTML
let html = node.parentElement.innerHTML
这篇关于使用Javascript / jQuery从iframe中选择HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!