Determine if an element in an iframe is visible on the screen

孤街醉人 提交于 2019-12-18 12:34:26

问题


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()?


回答1:


Here is an example of what you are trying to achieve.

Working example

Just the iframe

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.



来源:https://stackoverflow.com/questions/15250235/determine-if-an-element-in-an-iframe-is-visible-on-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!