让iframe自适应pc端和移动端页面
直接跳转导致网页卡顿所以才使用路由跳转打开iframe的方式
const fullPath = `/jumpUrl?url=${encodeURIComponent(linkHref)}`;
// 在新窗口中打开目标页面
window.open(fullPath, "_blank");
<template>
<div class="container">
<iframe
:src="url"
frameborder="0"
class="responsive-iframe"
allowfullscreen
scrolling="yes"
></iframe>
</div>
</template>
<script>
export default {
name: "Index",
data() {
return {
url: "",
};
},
created() {
//路由传递过来的参数
if (this.$route.query.url) {
this.url = decodeURIComponent(this.$route.query.url);
} else {
console.error("未接收到有效的 URL 参数");
}
},
mounted() {
this.$nextTick(() => {
this.adjustIframeSize();
// 强制启用缩放
const viewportMeta = document.createElement("meta");
viewportMeta.name = "viewport";
viewportMeta.content = "width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes";
document.head.appendChild(viewportMeta);
window.addEventListener("resize", this.throttle(this.adjustIframeSize, 200));
});
},
beforeDestroy() {
window.removeEventListener("resize", this.adjustIframeSize);
},
methods: {
adjustIframeSize() {
const container = document.querySelector(".container");
const iframe = document.querySelector(".responsive-iframe");
if (container && iframe) {
// 动态设置 iframe 的宽度和高度
iframe.style.width = `${container.offsetWidth}px`;
iframe.style.height = `${container.offsetHeight}px`;
const windowWidth = window.innerWidth;
if (windowWidth <= 768) {
const scaleRatio = windowWidth / 1280; // 原始网页的宽度为 1280px
iframe.style.transform = `scale(${scaleRatio})`;
iframe.style.transformOrigin = "left top";
iframe.style.width = `${100 / scaleRatio}%`; // 动态调整宽度
iframe.style.height = `${100 / scaleRatio}%`; // 动态调整高度
} else {
iframe.style.transform = "none";
iframe.style.width = "100%";
iframe.style.height = "100%";
}
}
},
throttle(func, wait) {
let timeout = null;
return (...args) => {
if (!timeout) {
timeout = setTimeout(() => {
func.apply(this, args);
timeout = null;
}, wait);
}
};
},
},
};
</script>
<style scoped>
html, body {
width: 100%;
height: 100%;
zoom: 0.5;
}
.container {
position: relative;
width: 100%;
height: 100vh; /* PC端全屏 */
overflow: hidden;
border: 1px solid #ccc;
/*display: flex; !* 使用 Flexbox 布局 *!*/
justify-content: center; /* 水平居中 */
transform-origin: center
}
.responsive-iframe {
width: 100%;
height: 100%;
border: none;
/*transform-origin: left top;*/
overflow: auto; /* 允许内部滚动 */
}
/* 手机端自适应 */
/* 添加缩放比例 */
@media (max-width: 768px) {
.responsive-iframe {
transform: scale(0.5); /* 根据需要调整缩放比例 */
transform-origin: left top; /* 确保缩放从左上角开始 */
width: 100%; /* 增加宽度以补偿缩放 */
height: 100%; /* 增加高度以补偿缩放 */
}
}
</style>