jQuery 如何获取 iframe 的 scrollTop
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1852518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get scrollTop of an iframe
提问by mkoryak
jQuery's scrollTop returns null when window is an iframe. Has anyone been able to figure out how to get scrollTop of an iframe?
当 window 是 iframe 时,jQuery 的 scrollTop 返回 null。有没有人能够弄清楚如何获得 iframe 的 scrollTop?
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
我的脚本在 iframe 本身中运行,父窗口在另一个域上,所以我无法访问 iframe 的 ID 或类似的东西
采纳答案by Doug Neiner
You can set scrollTop
by using this setup:
您可以scrollTop
使用此设置进行设置:
$("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).
因为不同的浏览器scrollTop
在不同的元素(body 或 html)上设置。
From the scrollTo plugin:
从 scrollTo 插件:
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:
但这在某些浏览器中可能仍然会失败。这是来自Ariel Flesher 的 jQuery 插件 scrollTo源代码的相关部分:
// 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.
确定 iframe 向下滚动的距离。
回答by Chris Jacob
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.
我在尝试在 iframe 中设置 scrollTop 时发现了这个问题......不完全是你的问题(你想得到),但这里有一个在 iframes 中的解决方案,供最终在这里尝试设置的人使用。
If you want to scroll to the top of the page this will NOT workinside an iframe:
如果您想滚动到页面顶部,这在 iframe 中不起作用:
$("html,body").scrollTop(0);
However, this will work:
但是,这将起作用:
document.getElementById("wrapper").scrollIntoView();
Or the equivilent with jQuery:
或者与 jQuery 等效:
$("#wrapper")[0].scrollIntoView();
For this markup (contained inside an iframe):
对于此标记(包含在 iframe 中):
<html>
<body>
<div id="wrapper">
<!-- lots of content -->
</div>
</body>
</html>
回答by Adam V.
$('#myIframe').contents().scrollTop()
回答by dudkaman
Good old javascript:
好老的javascript:
scrollTop = document.getElementById(IFRAME_ID).contentWindow.document.body.scrollTop;
回答by Peppeneppe
$('#myIframe').contents().scrollTop(0);
Only works with "0" as parameter
仅适用于“0”作为参数
回答by u5761591
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
第一个功能在桌面浏览器中工作成功。不适用于移动浏览器。所以我在 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
scrollIntoView()
在scrollIntoView 中查看- MDN
回答by eliprodigy
Cause you using iFrame you will need to use it that way with windows "message" event
因为您使用 iFrame,您需要以这种方式使用它与 Windows“消息”事件
Read here for more Info
阅读此处了解更多信息
On Child View (Iframe)
在子视图 (Iframe) 上
window.top.postMessage(0 + '$' + 'form-iframe-top', "*");
window.top.postMessage(0 + '$' + 'form-iframe-top', "*");
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 );
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
**注意我使用“*”作为分隔符,你可以使用任何东西
回答by Shubham Raturi
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.
我在 iframe 中遇到了同样的问题。我的整个网站都出现了白色 iframe 并且滚动不起作用所以我使用了这段代码并且它工作正常。
Step 1.put this code to your iframe
步骤 1.将此代码放入您的 iframe
var offsettop = 120;
window.parent.postMessage({"setAnchor": offsettop}, "*");
Step 2.put this code where your call you iframe
步骤 2.将此代码放在您调用 iframe 的位置
window.addEventListener('message', function(event) {
if(event.data['setAnchor']>0) {
var offsetHeight =event.data['setAnchor'];
jQuery('html, body').animate({
scrollTop: offsetHeight
}, 200);
}
})
回答by BenTheHumanMan
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:
我知道我在这里玩游戏迟到了,但我试图在移动设备上找到一长串列表。由于跨域冲突(并且我无权访问父窗口),scrollTop() 对我不起作用,但更改高度确实:
$('#someClickableElementInIFrame').on('click', function(e){
$("html body").animate({
'height' : "0"
}, {
complete: function(){
$("html body").css({
'height' : "auto"
})
}
})
});
回答by hypery2k
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%'
});
}
};