高度自适应iframe(Vue3)

https://juejin.cn/post/7283306395913617427

<script setup>
import { ref, onBeforeUnmount } from 'vue'

defineProps({
    srcdoc: {
        type: String,
        default: ''
    }
})

const iframe = ref()
const setIframeHeight = () => {
    setTimeout(() => {
        iframe.value.height =
            iframe.value?.contentWindow?.document?.documentElement?.offsetHeight || 0
    }, 150)
}
window.addEventListener('resize', setIframeHeight)
onBeforeUnmount(() => window.removeEventListener('resize', setIframeHeight))
</script>

<template>
    <iframe
        ref="iframe"
        :srcdoc="srcdoc"
        height="0"
        scrolling="no"
        @load="setIframeHeight"
    ></iframe>
</template>

<style scoped>
iframe {
    border: 0;
    width: 100%;
}
</style>

posted @ 2024-05-09 18:58  Felix_Openmind  阅读(87)  评论(0编辑  收藏  举报