场景:需要将vue嵌套在html页面的iframe中,根据vue页面的高度设置外层的iframe高度防止出现滚动条
以下为vue实现
// calculateHeight.js
export default {
mounted() {
const that = this;
window.onload = function () {
setTimeout(function () {
that.calculateHeight();
}, 2000);
};
this.calculateHeight();
},
updated() {
this.calculateHeight();
},
methods: {
calculateHeight() {
const getCurrentDocHeight = () => {
const cHeight = Math.max(
document.body.clientHeight,
document.documentElement.clientHeight
);
const sHeight = Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight
);
return Math.max(cHeight, sHeight);
};
const height = getCurrentDocHeight();
console.log("当前高度:", height);
console.log(window.parent.document.getElementsByTagName("iframe"));
const list = window.parent.document.getElementsByTagName("iframe");
const list2 = Array.from(list);
// 这里使用src进行匹配,你可以根据实际情况用ID匹配
const target = list2.find(
(ele) => ele.src.includes("http://localhost:8080/")
);
console.log(target);
target.style.height = height + "px";
},
},
};
网友评论