确定iframe中的元素是否在屏幕上可见 [英] Determine if an element in an iframe is visible on the screen
问题描述
我需要确定iframe中的元素是否在屏幕上可见。 (如果它在屏幕的可见部分)
我的意思是页面可以很长,用户必须滚动才能看到元素
index.html :
< html>
...
...
< iframe src =iframe.html/>
...
...
< / html>
< HTML>
...
...
< div id =element>< / div>
....
...
< script type =text / javascript>
var el = document.getElementById('element');
if(isElementVisible(el)){
//做某事
}
< / script>
< / html>
如何编写这样的函数isElementVisible()?
下面是您尝试实现的示例。
只需iframe 基本上,这个函数应该放在你的 iframe
中:
function isElementVisible(element)
{
var elementPosition = element.offset()。top;
var currentScroll = window.parent。$(iframe)。contents()。scrollTop();
var screenHeight = window.parent。$(iframe)。height();
var visibleArea = currentScroll + screenHeight;
return(elementPosition< visibleArea);
$ / code>
使用滚动事件处理函数触发您的检查。
$(window).scroll(function(){
if(isElementVisible(element))
//执行您的代码。
});
假设iframe与父框架位于同一个域中,为方便起见,我使用 jQuery 。
I need to determine if an element in an iframe is visible on the screen. (if it is on the visible part of the screen) I mean the page can be very long and user must scroll to see the element
index.html:
<html>
...
...
<iframe src="iframe.html" />
...
...
</html>
iframe.html:
<html>
...
...
<div id="element"></div>
....
...
<script type="text/javascript">
var el = document.getElementById('element');
if (isElementVisible(el)) {
// do something
}
</script>
</html>
How to write such a function isElementVisible()?
Here is an example of what you are trying to achieve.
Basically, this is the function that should go inside your iframe
:
function isElementVisible(element)
{
var elementPosition = element.offset().top;
var currentScroll = window.parent.$("iframe").contents().scrollTop();
var screenHeight = window.parent.$("iframe").height();
var visibleArea = currentScroll + screenHeight;
return (elementPosition < visibleArea);
}
Trigger your checks with a scroll event handler.
$(window).scroll(function(){
if( isElementVisible( element ) )
// Perform your code.
});
This works assuming the iframe is in the same domain as the parent frame. I use jQuery for convenience.
这篇关于确定iframe中的元素是否在屏幕上可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!