如何获得iframe的scrollTop [英] How to get scrollTop of an iframe
问题描述
当window是iframe时,jQuery的scrollTop返回null。有没有人能够弄清楚如何获得iframe的scrollTop?
更多信息:
我的脚本在iframe本身运行,父窗口在另一个域上,所以我无法访问iframe的ID或类似的东西
您可以使用此设置设置 scrollTop
:
$( HTML,身体)scrollTop的(25)。
所以你可以试试这样:
$( HTML,身体)scrollTop的();
因为不同的浏览器在不同的浏览器上设置 scrollTop
元素(正文或html)。
来自scrollTo插件:
但是在某些浏览器中可能仍会失败。以下是 Ariel Flesher的jQuery scrollTo插件源代码中的相关部分:
//黑客,黑客,黑客:)
//返回要滚动的真实元素(支持window / iframes ,文件和常规节点)
$ .fn._scrollable = function(){
返回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;
返回$ .browser.safari || doc.compatMode =='BackCompat'?
doc.body:
doc.documentElement;
});
};
然后你可以运行:
<$ p $ 。p>
$(窗口)._滚动()scrollTop的();
确定iframe向下滚动的距离。
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
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.
这篇关于如何获得iframe的scrollTop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!