高度自适应iframe(Vue3)
<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>
学而不思则罔,思而不学则殆!