【问题标题】:How to get the scroll position of content thats inside of an iframe如何获取 iframe 内内容的滚动位置
【发布时间】:2013-05-02 03:41:38
【问题描述】:

我有一个 html 页面,其中包含一个 iframe 加载一些任意页面。

<iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe>

我希望能够在 javascript/jquery 中的 iframe 中获取页面的滚动位置inside。当谈到 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)可以使用它的正确方法是什么?

【问题讨论】:

  • iframe 很棘手,因为出于安全原因,它们会限制您对其中正在发生的事情的访问。我认为您无法直接获取该信息。另一种选择可能是使 iframe 更大,并将 iframe 放在滚动 div 中,因此用户滚动 div 而不是 iframe 本身。我现在没有时间确保这能正常工作,祝你好运!
  • 如果您只想隐藏 iframe 的一部分 - 考虑使用 overflow:hidden; 样式元素包装 iframe 并将负 CSS top 添加到 iframe top: -20px; /*or some other value*/,这将隐藏 iframe 的一部分根本不想展示...

标签: javascript jquery html iframe scroll


【解决方案1】:

根据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>

【讨论】:

    【解决方案2】:

    您可以通过将滚动位置从子页面(iframe 内)更新到父页面来解决。

        // Child page
        $(window).scroll(function () {
            top.updateScrollPosition($('body').scrollTop(), $('body').scrollLeft());
        });
    

    还有父页面

        // Main page
        var topPos;
        var leftPos;
    
        function updateScrollPosition(top, left) {
            topPos = top;
            leftPos = left;
        }
    

    然后在任何你想要的地方使用topPos,leftPos。

    【讨论】:

    • 这意味着你可以访问框架的源代码
    【解决方案3】:

    要获取滚动位置,请使用窗口对象中存在的属性 scrollX 和 scrollY。

    write($("#siteframe").scrollX + ", " + $("#siteframe").scrollY);

    通过谷歌浏览器测试

    【讨论】:

    • 为跨域 iframe 返回 null 或 undefined。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多