vue+ts+iframe内嵌页面,动态设置iframe高宽

1,089 阅读1分钟

完整demo

<template>
  <div class="container">
  
    <iframe
      :src="src"
      ref="iframe"
      frameborder="no"
      border="0"
      marginwidth="0"
      marginheight="0"
      scrolling="yes"
      allowtransparency="yes"
    ></iframe>
    
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component({ name: '', components: {} })
export default class ToIframe extends Vue {
  private src: string = 'https://my.qidian.com/';
  private mounted() {
    // 这里就拿到了iframe的对象
    console.log(this.$refs.iframe);
    // 这里就拿到了iframe的window对象
    console.log((this.$refs.iframe as any).contentWindow); // .函数名

    // 获取iframe内嵌页面的宽高,动态设置iframe元素的宽高
    const iframeWidth = (this.$refs.iframe as any).contentWindow.outerWidth;
    const iframeHeight = (this.$refs.iframe as any).contentWindow.outerHeight;

    console.log(iframeWidth, 'w');
    console.log(iframeHeight, 'h');
    const frame = this.$refs.iframe as HTMLElement;
    frame.style.height = iframeHeight + 'px';
    frame.style.width = iframeWidth + 'px';
    // 设置iframe元素的缩放比例
    frame.style.transform = 'scale(' + 1920 / iframeHeight + ')';
  }
}
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
  background: url('~@/assets/img/home/bg-home.jpg') no-repeat;
  background-size: 100% 100%;
  iframe {
    transform-origin: 50% 0; //缩放原点
    transform: scale(1);
    left: 0;
    top: 0;
  }
}
</style>