引言
笔者是一名前端开发工程师,大部分开发工作都是在 H5 的世界里遨游。多年的 H5 开发经验总结了一些常用技巧,在这里分享给大家,希望在遇到同类问题时能给你提供思路和灵感,保护日益稀疏的头发。
HTML 相关
meta 标签
meta 元素可提供有关页面的元信息。下面是一些与移动端 H5 相关比较特殊的 meta 标签
<meta name="screen-orientation" content="portrait" />// 禁止屏幕旋转
<meta name="full-screen" content="yes" />// 全屏显示
<meta name="browsermode" content="application" />// UC应用模式,页面默认全屏
<meta name="x5-orientation" content="portrait" />// QQ强制竖屏
<meta name="x5-fullscreen" content="true" /> // QQ强制全屏
<meta name="x5-page-mode" content="app" /> // QQ应用模式
<meta name="renderer" content="webkit" />// 启用360浏览器的极速模式
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> // 优先使用 IE 最新版本和 Chrome
语义化标签
HTML5 语义化标签能够让页面的结构更清晰,有利于 SEO,并且能够帮助辅助技术更好的阅读和转译你的网页。推荐使用语义化标签编写 HTML
<header></header> // 定义文档的头部区域
<nav></nav> // 定义导航链接的部分
<main></main> // 定义文档的主体部分
<section></section> // 定义文档中的节
<footer></footer> // 定义页面的页脚
<aside></aside> // 定义页面的侧边栏内容
<article></article> // 定义一个文章区域
电话号码拨号与识别
使用 a 标签实现点击手机号码唤起拨号页面
<a href="tel:4009161060" class="phone">400-916-1060</a>
在 iOS Safari 浏览器上会将类似为电话号码的数字识别为电话链接,比如:
7 位数字,形如:1234567 带括号及加号的数字,形如:(+86)123456789 双连接线的数字,形如:00-00-00111 11 位数字,形如:13800138000
关闭识别
<meta name="format-detection" content="telephone=no" />
邮箱识别
使用 a 标签实现点击邮箱地址弹出邮件发送的功能
<a href="mailto:[email protected]" class="email">[email protected]</a>
Android 手机上会对符合邮箱格式的字符串进行识别,我们可以通过如下的 meta 来关闭邮箱的自动识别
<meta name="format-detection" content="email=no" />
CSS 相关
1px 边框
css 中的 1px 并不等于移动设备的 1px,是因为不同的手机有不同的像素密度。在 window 对象中有一个 devicePixelRatio 属性,他可以反应 css 中的像素与设备的像素比
devicePixelRatio 的官方的定义为:设备物理像素和设备独立像素的比例
完美实现 1px 的方法如下,兼容 DPR(设备像素比) 1-4 的设备
@line-color: #ccc;
[retina] {position: relative;
}
[retina]::before {position: absolute;box-sizing: border-box;width: 100%;height: 100%;font-size: 20px;content: ' ';pointer-events: none;
}
/* 设备像素比为 1 */
@media only screen and (-webkit-min-device-pixel-ratio: 1), only screen and (min-device-pixel-ratio: 1) {[retina]::before {width: 100%;height: 100%;transform: scale(1);transform-origin: 0 0;}[retina='line-bottom']::before {height: 1px;}[retina='line-top']::before {height: 1px;}[retina='line-left']::before {width: 1px;}[retina='rect-input']::before {border-width: