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

后端 未结 1 747
长情又很酷
长情又很酷 2020-12-30 14:36

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 t

相关标签:
1条回答
  • 2020-12-30 15:34

    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.

    0 讨论(0)
提交回复
热议问题