美文网首页
如何获取父级iframe的dom,并且设置高度

如何获取父级iframe的dom,并且设置高度

作者: cuttlefish | 来源:发表于2022-08-18 12:45 被阅读0次

场景:需要将vue嵌套在html页面的iframe中,根据vue页面的高度设置外层的iframe高度防止出现滚动条

以下为vue实现

// calculateHeight.js
export default {
  mounted() {
    const that = this;
    window.onload = function () {
      setTimeout(function () {
        that.calculateHeight();
      }, 2000);
    };
    this.calculateHeight();
  },
  updated() {
    this.calculateHeight();
  },
  methods: {
    calculateHeight() {
      const getCurrentDocHeight = () => {
        const cHeight = Math.max(
          document.body.clientHeight,
          document.documentElement.clientHeight
        );
        const sHeight = Math.max(
          document.body.scrollHeight,
          document.documentElement.scrollHeight
        );
        return Math.max(cHeight, sHeight);
      };

      const height = getCurrentDocHeight();
      console.log("当前高度:", height);
      console.log(window.parent.document.getElementsByTagName("iframe"));
      const list = window.parent.document.getElementsByTagName("iframe");
      const list2 = Array.from(list);
      // 这里使用src进行匹配,你可以根据实际情况用ID匹配
      const target = list2.find(
        (ele) => ele.src.includes("http://localhost:8080/")
      );
      console.log(target);
      target.style.height = height + "px";
    },
  },
};


相关文章

网友评论

      本文标题:如何获取父级iframe的dom,并且设置高度

      本文链接:https://www.haomeiwen.com/subject/btsegrtx.html