我有一个 html 页面,其中包含一个加载任意页面的 iframe。
<iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe>
我希望能够在 javascript/jquery 中获取页面的滚动位置在 iframe 中。当谈到 html/js 的东西时,我仍然有点新手,但我尝试了一些使用 scrollTop 和 scrollLeft 的不同变体,但没有成功。这是一个不起作用的:
write($("#siteframe").contents().scrollLeft() + ", " + $("#siteframe").contents().scrollTop());
这个从不写任何东西(write 是一种只附加到屏幕上文本的方法)。
如果我像这样删除 .contents()
:
write($("#siteframe").scrollLeft() + ", " + $("#siteframe").scrollTop());
它至少在屏幕上写了一些东西,但无论 iframe 中的实际滚动位置在哪里,它始终为 0,0。
在 javascript 中获取内容在 iframe 中的 x、y 位置以便我的外部页面(包含 iframe)可以使用它的正确方法是什么?
最佳答案
根据 this stack overflow post ,“结论是 iframe 内的任何内容都无法访问,甚至是在我的域上呈现的滚动条。”讨论很广泛。除非您有权访问该域,否则根本不可能从跨域 iframe 获取信息。
这是我失败的测试代码,以防有人想玩它:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<script>
function report() {
var frame_top = $('#siteframe').contents().find('body').scrollTop();
alert(frame_top);
}
</script>
<iframe id="siteframe" name="siteframe" style="width: 400px; height: 400px;" src="http://en.wikipedia.org/wiki/Hello_world"></iframe><br />
<button onclick="report()">Get Coords</button>
</body>
</html>
关于javascript - 如何获取iframe内内容的滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431704/