javascript - iframe取消边框后,如何高度自适应、求指教?

查看:132
本文介绍了javascript - iframe取消边框后,如何高度自适应、求指教?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

最近要自己搭个后台架子,原本DIV就能解决的问题,但变态老板接受不了URL跳转,因此最终想到了iframe加载,目前卡在高度自适应问题上了、、、求大神帮帮忙,如何在取消滚动条的情况下,让iframe里面的内容得到完整展示呢?

有做过的朋友麻烦指教下,最好是能有个简单的demo,先O(∩_∩)O谢谢啦、拜托!

解决方案

$(function() {

  // 自适应iframe高度
  if (window.frameElement) {

    var paddingPenalty = 60;
    var containerMinHeight = 1000;

    var $window = $(window);
    var $body = $(window.document.body);
    var $parentFrame = $(window.frameElement);
    var $parentFrameContainer = $parentFrame.parent();

    var parentFrameContainerOriginHeight = $parentFrameContainer.height();

    var parentFrameHeight = parentFrameContainerOriginHeight + paddingPenalty;

    // 自适应parent frame高度的function
    var resizeParentFrame = function(newHeight) {
      if ($parentFrame.is(':hidden')) {
        return;
      }
      if (parent.window.frameElement) {
        var $nestedParentFrame = $(parent.window.frameElement);
        var $nestedParentFrameContainer = $nestedParentFrame.parent();
        var nestedParentFrameHeight = $nestedParentFrameContainer.outerHeight();

        if ($nestedParentFrame.is(':hidden')) {
          return;
        }
        var tempHeight = newHeight;
        tempHeight += paddingPenalty;
        if (parentFrameHeight && (parentFrameHeight < nestedParentFrameHeight)) {
          $nestedParentFrameContainer.css('height', tempHeight <= parentFrameHeight ? parentFrameHeight : tempHeight);
        } else {
          $nestedParentFrameContainer.css('height', tempHeight <= nestedParentFrameHeight ? nestedParentFrameHeight : tempHeight);
        }
      }

      newHeight += paddingPenalty;
      $parentFrameContainer.css('height', newHeight <= containerMinHeight ? containerMinHeight : newHeight);
    }

    // iframe关闭的时候,取消iframe的高度
    $window.unload(function() {
      $parentFrameContainer.css('height', parentFrameContainerOriginHeight);
    });

    // 页面加载的完毕后,调整iframe高度
    //resizeParentFrame($body.height());
    resizeParentFrame(containerMinHeight);

    // 每隔500ms侦测body实际内容高度是否发生变化
    var checkBodyHeight = function(){
      var lastHeight = containerMinHeight, newHeight, timer;
      (function run(){

        if (!$parentFrame.is(':hidden')) {
          newHeight = $body.height();
          if (newHeight > parseInt($parentFrame.parent().css("height").replace("px", ""))) {
            $parentFrame.parent().css("height", newHeight);
          }
          if( newHeight > lastHeight ) {
            resizeParentFrame(newHeight);
          }
          lastHeight = newHeight + paddingPenalty;
        }

        timer = setTimeout(run, 200);

      })();
    }
    checkBodyHeight();

  }

});

这篇关于javascript - iframe取消边框后,如何高度自适应、求指教?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆