有时候,我们想让pc打开适配手机的h5,并且不变形,在不使用媒体查询的情况下,我们可以使用以下方式:
实现功能如下
pc打开
周围留空白,居中显示
当浏览器切换为手机模式/手机打开网址时
会变为手机模式
以下为主要代码
public 文件夹下 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script async="" src="https://www.google-analytics.com/analytics.js"></script>
<script async="" src="https://www.google-analytics.com/analytics.js"></script>
<script type="text/javascript">window.alert = console.log;</script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Title</title>
<meta http-equiv="Cache-Control" content="max-age=180">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<link rel="dns-prefetch" href="//m.360buyimg.com">
<meta name="format-detection" content="telephone=no">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no, viewport-fit=cover">
<meta http-equiv="x-dns-prefetch-control" content="on">
<script type="text/javascript">
// 如果判断下来是pc 那么跳转嵌入 iframe h5
~function () {
// 是不是移动端
var isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent);
// 在iframe内
var inIframe = window.frames.length != parent.frames.length;
if (!isMobile && !inIframe) {
window.location.href = "pc.html"
}
}()
</script>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
同级新建pc.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PC</title>
<script type="text/javascript">
// 如果判断下来是pc 那么跳转嵌入 iframe h5
~function () {
// 是不是移动端
var isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent);
console.log(isMobile);
if (isMobile) {
window.location.href = "index.html"
}
}()
</script>
</head>
<body style="background: #42b983">
<iframe style="background: white; display: block; margin: 0 auto;" width="414" height="716" src="./index.html" frameborder="0"></iframe>
</body>
</html>
主要实现是
index.html 在 iframe 内时就不要跳转了,上面逻辑写的很明白
---------------------------------------------------------------------------------------------------------------------------------
个人理解,光看js大概就是判断是什么设备,然后切换html。导入的那些我都不懂