前言
这两天因为项目遗留问题,服务器上有个包,没有那个包的代码,端口号改了之后,包不生效,需要重写一遍移动端h5页面展示在pc端上,之前包采用iframe方式实现,本人比较菜,采用iframe方式时,会出现页面的拉伸等问题,后采用Uniapp官网上的方式,做一个记录
实现方式
1.在根目录下创建一个html的模板文件,以template为例,代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<!-- Open Graph data -->
<!-- <meta property="og:title" content="Title Here" /> -->
<!-- <meta property="og:url" content="http://www.example.com/" /> -->
<!-- <meta property="og:image" content="http://example.com/image.jpg" /> -->
<!-- <meta property="og:description" content="Description Here" /> -->
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)'))
document.write('<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" />
<link rel="stylesheet" href="<%= BASE_URL %>static/adapt-pc/pc.css" />
</head>
<body>
<noscript>
<strong>Please enable JavaScript to continue.</strong>
</noscript>
<div id="app"></div>
<!-- uni-app 电脑端兼容模板容器 -->
<uni-adapt-pc></uni-adapt-pc>
<!-- uni-app 电脑端兼容模板 -->
<!-- 注意: 电脑端放置H5内容容器,helang-mobile-href 为固定标识不可修改 -->
<script type="text/html" id="tpl-adapt-pc">
<div class="container">
<iframe src="helang-mobile-href"></iframe>
</div>
</script>
<!-- uni-app 电脑端浏览兼容脚本文件 -->
<script type="text/javascript" src="<%= BASE_URL %>static/adapt-pc/pc.js"></script>
<!-- built files will be auto injected -->
</body>
</html>
2.在manifest.json文件中配置引入的自定义模板
3.在static目录下建立adapt-pc文件夹,下面建立 pc.css文件和pc.js文件
pc.css文件
body[adapt='pc']>*{
display: none !important;
}
body[adapt='pc']>uni-adapt-pc{
display: block !important;
}
body[adapt='pc'] {
margin: 0;
background-color: #fff;
width: 100vw;
height: 100vh;
}
body[adapt='pc'] uni-adapt-pc .container{
position: fixed;
width: 375px;
height: 100%;
z-index: 1;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
max-height: 680px;
box-sizing: border-box;
border: 1px solid #ddd;
box-shadow: 0 0 10px #ddd;
}
body[adapt='pc'] uni-adapt-pc iframe{
width: 100%;
height: 100%;
border: none;
}
pc.js文件
;(function(){
if(window.innerWidth < 768){
return;
}
var tpl = document.querySelector("#tpl-adapt-pc").innerHTML || '';
tpl = tpl.replace('helang-mobile-href',window.location.href);
document.querySelector("uni-adapt-pc").innerHTML = tpl;
document.body.setAttribute("adapt","pc");
})();