检查元素是否在iframe内的视口中

时间:2017-03-25 21:33:53

标签: javascript jquery iframe

我有一个包含iframe的页面,iframe只有在视口中才需要加载的元素很少。

但是iframe不可滚动,只有母版页有滚动。我已经编写了以下函数,但如果与母版页一起使用则无效。

function isVisible(a) {
        var b1 = a.getBoundingClientRect(),
        b={},
        c = window.innerWidth || doc.documentElement.clientWidth,
        d = window.innerHeight || doc.documentElement.clientHeight,
        e = function(a, b) {
            return document.elementFromPoint(a, b)
        };
        if(window.frameElement){
            var w = window.frameElement.getBoundingClientRect();
        //  d = window.innerHeight || doc.documentElement.clientHeight;
            for( var i in b1){
              b[i]=Math.abs(b1[i])+Math.abs(w[i])
            }
        }else{
            b=b1;
        }
    return !(b.right < 0 || b.bottom < 0 || b.left > c || b.top > d) && (a.contains(e(b.left, b.top)) || a.contains(e(b.right, b.top)) || a.contains(e(b.right, b.bottom)) || a.contains(e(b.left, b.bottom)))
}

请提前表明前进的方法。

1 个答案:

答案 0 :(得分:0)

这将推迟加载iframe内容,直到滚动到视图中。

JSFiddle Example

var $iframe = $("#iframe");
$(window).on("scroll", function() {
  // you should probably throttle or debounce this method; I didn't
  if (isScrolledIntoView($iframe[0])) {
     // assumes same origin for iframe
     // if iframe has window object and function "viewportUpdate" call function
     var iframeWindow = $iframe[0].contentWindow;         
     if (iframeWindow && iframeWindow.viewportUpdate)
     {
         var docViewTop = $(window).scrollTop();
         var docViewBottom = docViewTop + $(window).height();
         iframeWindow.viewportUpdate(docViewTop, docViewBottom);
     }
  }
});

// from http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling
function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

iframe内容使用此方法来实现您的魔力:

function viewportUpdate(docViewTop, docViewBottom)
{
   // do your magic here.. whatever that is
   // for example, loop over each "img" element and log to console if in view
   $("img").each(function()
   {
       var elemTop = $(elem).offset().top;
       var elemBottom = elemTop + $(elem).height();
       var elementIsInView = (elemBottom <= docViewBottom) && (elemTop >= docViewTop);
       if (elementIsInView)
       {
           console.log("iframe img element is in view");
       }
   });
}