最近在项目中遇到一个需求需要在一个项目中直接引用另一个项目,尝试各种情况无果后选择了iframe。现将调用过程中遇到的问题做一个分享。
router.go()的失效问题
此情况主要适用于更改iframe中src值以后导致的路由跳转混乱。
详细描述:当多次更改iframe->src属性后,调用router.go(-1),不能实现路由后退上一级,而是将iframe当作一个窗口文档,调用了该窗口文档的window.history.go(-1),并未更改父级项目的路由后退功能。
解决办法:
不通过改变iframe->src属性值去访问具体内容,采用window.location.replace(url)更改iframe将访问的内容,具体代码如下:
<!-- A.html -->
<template>
<iframe ref="iframe" scrolling="auto" width="100%" height="100%" frameborder="0" ></iframe>
</template>
<script>
this.$refs.iframe.contentWindow.location.replace(val)
</script>
这有一个iframe标签,src指向的是一个路径(图片路径)
在浏览器上用审查元素看一下:1.iframe 2.#document 3.html 4.head 5.body 6.body.img
那么问题来了,怎么给iframe里边的img设置宽和高呢?
- let iframe =.document.getElementById(“preview”);//通过id找到想要元素
- let iwindow = iframe.contentWindow;//获取iframe的window对象
- 以下很是致命,切记:在iframe加载完毕才能拿到里面的所有document树(代码第五行)
- let idoc = iwindow.document; //获取iframe的document
- let img = idoc.getElementsByTagName(‘img’)[0];//搜索指定元素的后代,不包括自身,【0】第一个’img’
- img.width = iframe.clientWidth;将iframe的宽赋值给图片,高也是一样。
let iframe = document.getElementById("preview");//通过id找到想要元素
console.log("iframe",iframe);
let iwindow = iframe.contentWindow;
iframe.addEventListener('load',function () {
// 在iframe加载完毕才能拿到里面的所有document树
//很重要,必须放置在load函数里
//切记,坑深勿踩
let idoc = iwindow.document;
console.log("iwindow", iwindow);
console.log("idoc", idoc);
let img = idoc.getElementsByTagName('img')[0];
if (img) {
if(img.width >= img.height){
img.width = iframe.clientWidth;
let top = (iframe.clientHeight - img.height) / 2;
img.style.marginTop = top + "px";
}else {
img.height = iframe.clientHeight;
let left = (iframe.clientWidth - img.width) / 2;
img.style.marginLeft = left + "px";
}
}
})
clientWidth = width+左右padding;
clientHeigh = height + 上下padding ;
clientTop = boder.top(上边框的宽度);
clientLeft = boder.left(左边框的宽度);
marginTop:设置一个p元素的上部边距
marginLeft:设置一个p元素的左部边距
以下内容可加在合适的位置控制台输出查看
// console.log("window",iwindow);//获取iframe的window对象
// console.log("document",idoc); //获取iframe的document
// console.log("html",idoc.documentElement);//获取iframe的html
// console.log("head",idoc.head); //获取head
// console.log("body",idoc.body); //获取body
// console.log("img",idoc.getElementsByTagName('img'[0]));//获取img
// console.log("iframeWidth",iframe.clientWidth);//获取iframe的宽
// console.log("imgWidth",idoc.body.getElementsByTagName('img'[0]));//获取img的宽