如何获取iframe的scrollTop

发布于 2024-08-14 02:30:41 字数 156 浏览 10 评论 0 原文

当window是iframe时,jQuery的scrollTop返回null。有谁能弄清楚如何获取 iframe 的scrollTop 吗?

更多信息:

我的脚本在 iframe 本身中运行,父窗口位于另一个域上,因此我无法访问 iframe 的 ID 或类似的内容

jQuery's scrollTop returns null when window is an iframe. Has anyone been able to figure out how to get scrollTop of an iframe?

more info:

my script is running in the iframe itself, the parent window is on another domain, so I can't access the ID of the iframe or anything like that

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

一抹微笑 2024-08-21 02:30:41

我在尝试在 iframe 内设置scrollTop 时发现了这个问题...不完全是你的问题(你想要获取),但这里有一个 iframe 内的解决方案,供那些最终也在这里尝试设置的人使用。

如果您想滚动到页面顶部,在 iframe 内这将不起作用

$("html,body").scrollTop(0);

但是,这将起作用:

document.getElementById("wrapper").scrollIntoView();

或者与 jQuery 等效:

 $("#wrapper")[0].scrollIntoView();

对于此标记(包含在 iframe 内):

<html>
  <body>
    <div id="wrapper">
      <!-- lots of content -->
    </div>
  </body>
</html>

I found this question while trying to SET scrollTop inside an iframe... not exactly your question (you wanted to GET) but here's a solution inside iframes for people that also end up here trying to SET.

If you want to scroll to the top of the page this will NOT work inside an iframe:

$("html,body").scrollTop(0);

However, this will work:

document.getElementById("wrapper").scrollIntoView();

Or the equivilent with jQuery:

 $("#wrapper")[0].scrollIntoView();

For this markup (contained inside an iframe):

<html>
  <body>
    <div id="wrapper">
      <!-- lots of content -->
    </div>
  </body>
</html>
无言温柔 2024-08-21 02:30:41
$('#myIframe').contents().scrollTop()
$('#myIframe').contents().scrollTop()
才能让你更想念 2024-08-21 02:30:41

您可以使用以下设置来设置 scrollTop

$("html,body").scrollTop(25);

所以您可以尝试像这样获取它:

$("html,body").scrollTop();

因为不同的浏览器在不同的元素(body 或 html)上设置 scrollTop

来自scrollTo插件:

但这在某些浏览器中可能仍然会失败。以下是Ariel Flesher 的 jQuery 滚动To 插件源代码中的相关部分:

// Hack, hack, hack :)
// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
$.fn._scrollable = function(){
  return this.map(function(){
    var elem = this,
      isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

    if( ! isWin ) {
      return elem;
    }


    var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;

     return $.browser.safari || doc.compatMode == 'BackCompat' ?
       doc.body : 
       doc.documentElement;
  });
};

然后您可以运行:

$(window)._scrollable().scrollTop();

确定 iframe 向下滚动的距离。

You can set scrollTop by using this setup:

$("html,body").scrollTop(25);

So you could try getting it like this:

$("html,body").scrollTop();

Because different browsers set the scrollTop on different elements (body or html).

From the scrollTo plugin:

But that will probably still fail in certain browsers. Here is the relevant section from the source code of Ariel Flesher's scrollTo plugin for jQuery:

// Hack, hack, hack :)
// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
$.fn._scrollable = function(){
  return this.map(function(){
    var elem = this,
      isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

    if( ! isWin ) {
      return elem;
    }


    var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;

     return $.browser.safari || doc.compatMode == 'BackCompat' ?
       doc.body : 
       doc.documentElement;
  });
};

You may then run:

$(window)._scrollable().scrollTop();

To determine how far the iframe has scrolled down.

擦肩而过的背影 2024-08-21 02:30:41

好旧的 JavaScript:

scrollTop = document.getElementById(IFRAME_ID).contentWindow.document.body.scrollTop;

Good old javascript:

scrollTop = document.getElementById(IFRAME_ID).contentWindow.document.body.scrollTop;
姜生凉生 2024-08-21 02:30:41
$('#myIframe').contents().scrollTop(0);

仅适用于“0”作为参数

$('#myIframe').contents().scrollTop(0);

Only works with "0" as parameter

你列表最软的妹 2024-08-21 02:30:41

我尝试过

$('#myIframe').contents().scrollTop(0);

 let scrollTop = document.getElementById(IFRAME_ID).contentWindow.document.body.scrollTop;

一个功能在桌面浏览器中成功运行。无法在移动浏览器中工作。所以我

$("#ButtonId").click(function() {
        var win = document.getElementById(IFRAMEID).contentWindow;
        var scrollTop = win.document.documentElement.scrollTop || win.pageYOffset || win.document.body.scrollTop;
        // scrollTop can getted
        if (scrollTop) {
            win.document.documentElement.scrollTop = 0;
            win.pageYOffset = 0; // safari
            win.document.body.scrollTop = 0;
        } else {
            win.document.body.scrollIntoView(true); // let scroll to the target view 
        }
    });

scrollIntoView() 视图 的另一个函数“nofollow noreferrer”>scrollIntoView - MDN

I have try to

$('#myIframe').contents().scrollTop(0);

and

 let scrollTop = document.getElementById(IFRAME_ID).contentWindow.document.body.scrollTop;

the first function work success in desktop browser. not working in mobile browser. so I use another function with scrollIntoView

$("#ButtonId").click(function() {
        var win = document.getElementById(IFRAMEID).contentWindow;
        var scrollTop = win.document.documentElement.scrollTop || win.pageYOffset || win.document.body.scrollTop;
        // scrollTop can getted
        if (scrollTop) {
            win.document.documentElement.scrollTop = 0;
            win.pageYOffset = 0; // safari
            win.document.body.scrollTop = 0;
        } else {
            win.document.body.scrollIntoView(true); // let scroll to the target view 
        }
    });

scrollIntoView() view in scrollIntoView - MDN

活泼老夫 2024-08-21 02:30:41

我在 iframe 中也遇到了同样的问题。我的整个网站出现白色 iframe 并且滚动不起作用
所以我使用了这段代码并且工作正常。

第 1 步。将此代码放入您的 iframe

var offsettop =  120;
window.parent.postMessage({"setAnchor": offsettop}, "*");

第 2 步。将此代码放入您调用 iframe 的位置

window.addEventListener('message', function(event) {
  if(event.data['setAnchor']>0) {
    var offsetHeight =event.data['setAnchor'];
    jQuery('html, body').animate({
      scrollTop: offsetHeight
    }, 200);
  } 
})

I have faced the same problem in my iframe. My whole website comming white iframe and scrolling not working
So I used this code and it's work fine.

Step 1. put this code to your iframe

var offsettop =  120;
window.parent.postMessage({"setAnchor": offsettop}, "*");

Step 2. put this code where your call you iframe

window.addEventListener('message', function(event) {
  if(event.data['setAnchor']>0) {
    var offsetHeight =event.data['setAnchor'];
    jQuery('html, body').animate({
      scrollTop: offsetHeight
    }, 200);
  } 
})
优雅的叶子 2024-08-21 02:30:41

或使用这个

sample.showLoader = function() {
// show cursor wait
document.getElementsByTagName('body')[0].style.cursor = 'wait';
var loader = $('#statusloader');
// check if we're runnign within an iframe
var isIframe = top !== self;
if (isIframe) {
    var topPos = top.pageYOffset + 300;
    // show up loader in middle of the screen
    loader.show().css({
        top : topPos,
        left : '50%'
    });
} else {
    // show up loader in middle of the screen
    loader.show().css({
        top : '50%',
        left : '50%'
    });
}
};

or use this one

sample.showLoader = function() {
// show cursor wait
document.getElementsByTagName('body')[0].style.cursor = 'wait';
var loader = $('#statusloader');
// check if we're runnign within an iframe
var isIframe = top !== self;
if (isIframe) {
    var topPos = top.pageYOffset + 300;
    // show up loader in middle of the screen
    loader.show().css({
        top : topPos,
        left : '50%'
    });
} else {
    // show up loader in middle of the screen
    loader.show().css({
        top : '50%',
        left : '50%'
    });
}
};
窗影残 2024-08-21 02:30:41

我知道我在这里玩游戏迟到了,但我试图在移动设备上解决这个问题。
由于跨域冲突(并且我无权访问父窗口),scrollTop() 对我不起作用,但更改高度确实如此:

$('#someClickableElementInIFrame').on('click', function(e){
      $("html body").animate({
      'height' : "0"
    }, {
        complete: function(){
          $("html body").css({
            'height' : "auto"
            })
          }
      })
});

I know I'm late to the game here, but I was trying to figure this out for a long list on mobile.
scrollTop() wasn't working for me due to cross-domain conflicts(and I didn't have access to parent window), but changing the height did:

$('#someClickableElementInIFrame').on('click', function(e){
      $("html body").animate({
      'height' : "0"
    }, {
        complete: function(){
          $("html body").css({
            'height' : "auto"
            })
          }
      })
});
猫七 2024-08-21 02:30:41

因为您使用 iFrame,所以您需要将其与 Windows“消息”事件一起使用,

请阅读此处了解更多信息 信息

子视图(Iframe)

window.top.postMessage(0 + '

在家长视图中

 window.addEventListener("消息",function(e) {
       if (e && e.data && typeof e.data == "string" && e.data != undefined) {
         var data = e.data.split("$");
             if (data.length == 2) {
               var 滚动高度 = 数据[0], iframe_id = 数据[1];
               if(iframe_id=="form-iframe-top"){
                   window.scrollTo(0,scroll_height);
                   返回;
                  }
               }
          }
         },
        错误的
      );

**注意我使用“*”作为分隔符,你可以使用任何东西

+ 'form-iframe-top', "*");

在家长视图中


**注意我使用“*”作为分隔符,你可以使用任何东西

Cause you using iFrame you will need to use it that way with windows "message" event

Read here for more Info

On Child View (Iframe)

window.top.postMessage(0 + '

On Parent View

   window.addEventListener("message",function(e) {
       if (e && e.data && typeof e.data == "string" && e.data != undefined) {
         var data = e.data.split("$");
             if (data.length == 2) {
               var scroll_height = data[0], iframe_id = data[1];
               if(iframe_id=="form-iframe-top"){
                   window.scrollTo(0,scroll_height);
                   return;
                  }
               }
          }
         },
        false
      );

**Note i used "*" as separator you can use anything

+ 'form-iframe-top', "*");

On Parent View


**Note i used "*" as separator you can use anything

强者自强 2024-08-21 02:30:41

另一个提示:除了 this.myIframe.contentWindow.document.body.scrollTop 之外,您还可以从 addEventListener 中的事件获取scrollTop。然而,像“document.getElementById('iframe').scrollTop”之类的东西将始终不返回任何内容。

<iframe id='iframe' src={ 'https://myurl.org'} height={'100%'} width={'100%'} ref={ref => this.termsIframe = ref}

...

this.myIframe.contentWindow.document.addEventListener('scroll', (event) => {
  console.log('scrollTop: ', event.target.body.scrollTop);
}, false);

顺便说一句,我正在使用 React Native Web,这就是 ref 标签的来源

Another tip: You can also get scrollTop from the event in addEventListener in addition to this.myIframe.contentWindow.document.body.scrollTop. However, something like "document.getElementById('iframe').scrollTop" will always return nothing.

<iframe id='iframe' src={ 'https://myurl.org'} height={'100%'} width={'100%'} ref={ref => this.termsIframe = ref}

...

this.myIframe.contentWindow.document.addEventListener('scroll', (event) => {
  console.log('scrollTop: ', event.target.body.scrollTop);
}, false);

I'm using React Native Web by the way, that's where the ref tag comes from

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文