本文介绍了确定iframe中的元素是否在屏幕上可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定iframe中的元素是否在屏幕上可见。 (如果它在屏幕的可见部分)
我的意思是页面可以很长,用户必须滚动才能看到元素



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)){
//做某事
}
< / script>
< / html>

如何编写这样的函数isElementVisible()?

解决方案

下面是您尝试实现的示例。





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中的元素是否在屏幕上可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 16:10
查看更多