Is there a way to access whether a portion of a webpage is being rendered on screen or not via Javascript?

别说谁变了你拦得住时间么 提交于 2019-12-11 05:07:57

问题


Currently our logic runs within an iframe on clients pages. We have the request to now detect whether that iFrame is currently in the viewing window or not (scrolled off-screen).

I just had an idea that this might be something that the GPU might already have which would allow for it to provide better performance on the page with regards to what it is rendering and I wanted to know if anyone was aware of whether this data was accessible via an API/lib such as OpenGL.

I am aware that providing actual pixel info, could be a large security issue, however just having access to whether or not a specific iFrame was being rendered would be helpful for viewability detection.

Is anyone aware of whether there is a way to do this? Current reading so far is not showing this as being possible, but I am continuing my search and thought I would post here as well.

Any info or direction would be helpful. Thanks!


回答1:


You can calculate if the object is inside your viewport or not.

http://plnkr.co/edit/91gybbZ7sYVELEYvy1IK?p=preview

$(document).ready(function() {
  myElement = $('.someObject');
  window.onscroll = function() {

    var screenTop = $(window).scrollTop();
    var screenBottom = screenTop + $(window).height();    
    var elTop = $(myElement).offset().top;
    var elBottom = elTop + $(myElement).height();

    var info = 'screenTop:' + screenTop + ' screenBottom:' + screenBottom + ' elTop:' + elTop + ' elBottom:' + elBottom;

    if((elBottom <= screenBottom) && (elTop >= screenTop)) {
      $('.info').html('Element is in view + <small>' + info + '</small>');
    } else {
      $('.info').html('Element is out of view + <small>' + info + '</small>');
    }

  }
})


来源:https://stackoverflow.com/questions/39299291/is-there-a-way-to-access-whether-a-portion-of-a-webpage-is-being-rendered-on-scr

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