简体   繁体   English

使用IFrame和Javascript滚动父页面

[英]Using IFrame and Javascript to scroll parent page

I'm looking for some help on what should be a basic script (I think), but I can't quite figure it out myself.. 我正在寻找一些有关基本脚本的帮助(我认为),但我自己还不太清楚。

I have a page, with an iFrame, displaying a page that I only have access to the header. 我有一个带有iFrame的页面,显示一个我只能访问标题的页面。 I'd like to make it so that when someone clicks ANY link ( tag) in the iFrame window, it scrolls my parent page to the top (or a specific location). 我要这样做,以便当有人单击iFrame窗口中的ANY链接(标记)时,它会将我的父页面滚动到顶部(或特定位置)。 Is this possible? 这可能吗?

Edit: Also, if it's important, I'm already using David Bradshaw's iFrame resizer script to resize the frame on the fly, which uses postmessage to communicate frame->page. 编辑:此外,如果重要的话,我已经在使用David Bradshaw的iFrame调整大小脚本来动态调整框架的大小,该脚本使用后消息来传达框架->页面。 https://github.com/davidjbradshaw/iframe-resizer https://github.com/davidjbradshaw/iframe-resizer

Edit2: The parent window and iframe window are cross-domain Edit2:父窗口和iframe窗口是跨域的

See Trigger events in iframe's parent window 请参阅iframe的父窗口中的触发事件

Add some JS to your iframe page: 在您的iframe页面中添加一些JS:

$(document).ready(function(){
    $('a').click(function(){
        window.parent.$(window.parent.document).trigger('scroll');
    });
});

Then on the parent page: 然后在父页面上:

$(document).bind('complete', function(){
    //Add scroll code.
});

You could use post message to do something similar, but if you control both pages and they are on the same domain, this should work. 您可以使用帖子消息执行类似的操作,但是如果您同时控制两个页面并且它们都在同一域中,则应该可以使用。 If they are on different domains (which you didn't specify) you are stuck using postMessage which I believe isn't entirely cross-browser complient and therefore won't work on all settings and there really isn't a fallback. 如果它们位于不同的域(您未指定)上,那么您将使用postMessage,我认为它不是完全跨浏览器兼容的,因此将无法在所有设置上使用,并且实际上没有后备功能。

If you want to use postMessage and you are using a plugin, just do something like 如果您想使用postMessage并且正在使用插件,则只需执行以下操作即可

window.addEventListener("message",function(event){
    if(event.origin == 'http://yourdomain.com'){
        if(event.data == 'messageString'){
            //Add scroll code
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM