Vue中優雅的更改iframe嵌入頁面的樣式
阿新 • • 發佈:2022-12-04
通過外部引入css檔案來控制嵌入頁面的樣式
公共iframe元件封裝
傳入屬性:
嵌入頁面路徑
css檔名稱(預設放在/static/css/下),預設css檔名可以自己定義,在確定嵌入頁面不多,相互之間的css屬性不會衝突的情況下,可以使用一個css檔案
<template> <div class="wrapper-c"> <div style="height: 100%" v-bkloading="{ isLoading: loading, opacity: 1, zIndex: 10 }"> <iframe id="fram_box" @load="loadFrame" :src="url" > </iframe> </div> </div> </template> <script> export default { name: 'common-iframe', props: { url: String, link: { type: String, default: 'frame_reset' } }, data() { return { loading: true } }, mounted() { const close = this.closeLoading $('#fram_box').load(() => { close() }) }, methods: { closeLoading() { this.loading = false }, // loadFrame函式是iframe載入完成後回撥函式 loadFrame() { // 獲取iframe節點 const iframeBox = document.getElementById('fram_box') // 獲取iframe html檔案 const doc = iframeBox.contentWindow.document // 獲取iframe html檔案head const head = doc.getElementsByTagName('head') // 新建link標籤 const linkTag = document.createElement('link') // 設定link標籤id linkTag.id = 'newstyle' // link標籤引入css檔案的地址 ;window.STATIC_URL 是全域性變數,指向靜態資源目錄,需要自己指定 linkTag.href = `${window.STATIC_URL}css/${this.link}.css` // 設定link標籤屬性 linkTag.setAttribute('rel', 'stylesheet') // 設定link標籤屬性 linkTag.setAttribute('type', 'text/css') // 將link標籤新增進iframe html檔案的head裡 head[0].append(linkTag) } } } </script> <style lang="scss" scoped> .wrapper-c { width: calc(100%); height: 100%; margin-left: 0; #fram_box { height: 100%; width: 100%; border-width: 0px; } } </style>
父元件使用
<template> <div id="wraper-p"> <common-iframe :url="infoUrl" :link="'health_adviser'"></common-iframe> </div> </template> <script> import commonIframe from '../components/commonIframe' export default { name: 'overview', components: { commonIframe }, data() { return { infoUrl: '【頁面路徑】' } } } </script> <style lang="scss" scoped> #wraper-p{ width: 100%; height: calc(100vh - 92px); box-sizing: border-box; overflow: hidden; } </style>
參考:
https://blog.csdn.net/sinat_32546159/article/details/119738108
https://juejin.cn/post/6844904180792967182