同一个 URL 如何实现适配手机和电脑?
User-Agent
- 通过 User-Agent 前端判断设备类型并跳转
javascript
const userAgent = navigator.userAgent.toLowerCase()
// 判断是否是移动设备
const isMobile = /mobile|android|iphone|ipad|phone/i.test(userAgent)
if (isMobile) {
// 跳转到 H5 页面
window.location.href = '/h5'
} else {
// 跳转到 Web 页面
window.location.href = '/web'
}优势:
- 前端实现简单,灵活性强。
- 无需后端介入。
劣势:
- 对 SEO 不友好,搜索引擎无法正确索引页面。
- 用户体验稍差,需加载完成后再跳转。
- 后端通过 User-Agent 判断设备类型
利用后端读取 HTTP 请求头中的 User-Agent,判断用户设备并返回相应页面或资源。
javascript
const express = require('express')
const app = express()
app.get('/', (req, res) => {
const userAgent = req.headers['user-agent'].toLowerCase()
if (/mobile|android|iphone|ipad|phone/i.test(userAgent)) {
// 返回 H5 页面
res.sendFile(__dirname + '/h5/index.html')
} else {
// 返回 Web 页面
res.sendFile(__dirname + '/web/index.html')
}
})
app.listen(3000, () => {
console.log('Server is running at <http://localhost:3000>')
})优势:
- 服务端判断,不依赖前端,适合 SEO。
- 可根据需求直接返回页面或资源。
劣势:
- 增加了服务端逻辑处理,配置复杂度略高。
- Nginx 通过 User-Agent 判断设备类型
Nginx 是高性能的 HTTP 服务器,可以通过其内置的 $http_user_agent 变量判断设备类型,并实现页面跳转或代理。
nginx
server {
listen 80;
server_name example.com;
# 定义 User-Agent 的正则规则
set $mobile_request 0;
if ($http_user_agent ~* '(Mobile|Android|iPhone|iPad|Phone)') {
set $mobile_request 1;
}
# 重定向到不同的页面
location / {
if ($mobile_request = 1) {
rewrite ^/$ /h5/index.html break; # 移动设备跳转到 H5 页面
}
rewrite ^/$ /web/index.html break; # PC 设备跳转到 Web 页面
}
# 定义 H5 页面文件路径
location /h5/ {
root /path/to/your/h5/app;
index index.html;
}
# 定义 Web 页面文件路径
location /web/ {
root /path/to/your/web/app;
index index.html;
}
}优势:
- 性能高效,直接在 Nginx 层判断和处理。
- 避免用户跳转,体验更佳。
- 适合静态资源部署。
劣势:
- 配置稍复杂,需要熟悉 Nginx 配置语法。
- 需考虑缓存和 CDN 的影响。
响应式设计(CSS 媒体查询)
当 PC 和 H5 页面功能相似,仅布局不同时,可以通过 CSS 媒体查询实现响应式页面,无需分离页面。
css 判断(@media) js 逻辑(matchMedia)
优势:
- 无需跳转或后端逻辑,所有用户访问同一页面。
- 减少开发和维护成本。
劣势:
- 仅适合功能相似的页面。
- 复杂度增加时,可能导致代码臃肿。
流体布局
百分比 相对单位 rem flex grid lfr