Bootstrap的Tab可以完全替代<iframe>标签吗

html-css011

Bootstrap的Tab可以完全替代<iframe>标签吗,第1张

不可以,<iframe>中的 CSS/JS 环境都是与父窗口相互隔离的。

不主动旦龚测夹爻蝗诧伟超连进行跨 context 通信的话两个窗口的样式和逻辑不会互相影响。

1、iframe里的也是一个独立的网页,只有它自己的css或它引用的css才对它有效。

当然你可以在父页面用js来控制。

2、使用css可以设置百分比,如width:100%;

IFRAME 里面的内容是在IFRAME 页面中的,可以使用js精确设置。

react 嵌入 iframe 主要是为了隔离富文本,避免跟宿主环境的样式、变量等造成污染。

情况1:后端返回一个完整的网页,前端直接 `<iframe src="$url"></iframe>` 就可以了。

情况2:后端返回内容不可控 (比如以下例子)。

用法:

index.tsx:

export default function Iframe () {

const contentIFrameRef = useRef<HTMLIFrameElement>(null)

const [iframeHeight, setIframeHeight] = useState(0)

useEffect(() =>{

$api.xxxxx(xxx)

.then((res) =>{

const iframe: HTMLIFrameElement | null = contentIFrameRef.current

if (iframe &&iframe.contentWindow) {

const iframeDocument = iframe.contentWindow.document

// 写入内容(这里举例的 iframe 内容是请求接口后返回 html,也就是 res,比如 res="<h1>标题</h1>")

iframeDocument.write(res)

// 如果需要 css,写入 css,此处的 css 是写在根目录里(与 index.html 同级)

if (!(iframeDocument.getElementsByTagName('link')[0])) {

const link = iframeDocument.createElement('link')

link.href = process.env.PUBLIC_URL + '/template.css'

link.rel = 'stylesheet'

link.type = 'text/css'

iframeDocument.head.appendChild(link)

}

// 这里动态计算 iframe 的 height,这里举例 300px

setIframeHeight(300)

}

})

}, [])

return (

<iframe

ref={contentIFrameRef}

title="iframe"

style={{ width: 1120, border: 0, height: <strong>iframeHeight</strong>}}

sandbox="allow-same-origin allow-scripts allow-popups allow-forms"

scrolling="auto"

></iframe>

)

}

如果后端把 iframe 的内容放在服务端,返给前端一个 url,可以直接 <iframe src={Url}></iframe>