vue 3 修改iframe 内部样式
Vue 3 中修改 iframe 内部样式的方法如下:
- 首先,在 Vue 组件中创建一个 ref 来引用 iframe 元素:
<template>
<div>
<iframe ref="myIframe"></iframe>
</div>
</template>
<script>
export default {
mounted() {
const iframe = this.$refs.myIframe;
// 在这里对 iframe 进行操作
}
}
</script>
- 使用
contentWindow属性来获取 iframe 的 window 对象,然后使用contentDocument属性获取 iframe 内部的 document 对象:
mounted() {
const iframe = this.$refs.myIframe;
const iframeWindow = iframe.contentWindow;
const iframeDocument = iframeWindow.document;
// 在这里对 iframe 内部进行操作
}
- 使用
querySelector方法来选择需要修改样式的元素,并使用style属性来修改样式:
mounted() {
const iframe = this.$refs.myIframe;
const iframeWindow = iframe.contentWindow;
const iframeDocument = iframeWindow.document;
const targetElement = iframeDocument.querySelector('.target-element');
targetElement.style.backgroundColor = 'red';
}
在这个例子中,我们选择了一个类名为 target-element 的元素,并将其背景颜色修改为红色。
注意:由于同源策略的限制,如果 iframe 的源与父页面的源不同,可能无法直接操作 iframe 内部的内容。在这种情况下,您可以考虑使用 postMessage 方法来与 iframe 进行通信,从而修改样式
原文地址: https://www.cveoy.top/t/topic/iN3U 著作权归作者所有。请勿转载和采集!