Web 交互 & 移动端适配
网页分享到各平台
QQ 空间分享
js
const url = 'https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey';
const params = new URLSearchParams({ url: location.href, title: document.title, summary: document.title });
window.open(`${url}?${params}`, '_blank', 'width=750,height=520');微信分享
微信内 JS-SDK 的 wx.updateAppMessageShareData — 仅限微信内浏览器。非微信环境只能复制链接提示用户手动分享。
移动端唤起 App
- 微信:
weixin://URL Scheme - QQ:
mqq://URL Scheme - URL Scheme 在 JS 中通过
window.location.href跳转
注意: 微信 iOS 对非用户触发的 scheme 跳转有限制。降级方案:
js
// iframe 降级(避免页面跳转)
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = 'weixin://';
document.body.appendChild(iframe);
setTimeout(() => document.body.removeChild(iframe), 1000);移动端 vs 桌面端检测
js
const isMobile = /Mobi|Android|iPhone|iPad|iPod/i.test(navigator.userAgent)
|| (navigator.maxTouchPoints > 1 && /Mac OS/i.test(navigator.userAgent));iPadOS 13+ 的 UA 和桌面 Mac 一样,需额外通过 maxTouchPoints 判断。
移动端调试
vConsole: 腾讯出品的移动端调试神器,类似 Chrome DevTools 迷你版。通过 CDN 引入或 index.html 条件加载,可查看 console、network、element、storage。
html
<script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
<script>new VConsole();</script>touch 和 click 事件冲突
问题: 移动端绑定了 touchstart 和 click,触发时两个都执行。
解决:
- 使用
e.preventDefault()阻止后续的 click(但会影响滚动) - 设置时间戳判断:touchstart 和 touchend 间隔 < 200ms 视为 tap,忽略 click
- 使用
pointer-events或touch-actionCSS 属性控制 - 最省事:设置
touch-action: manipulationCSS 属性消除 300ms 延迟,或 viewport 加user-scalable=no。FastClick 已废弃(Chrome 32+/iOS 9.3+ 无需),不再推荐
蒙层滚动穿透
问题: 弹窗/蒙层显示时,背景页面仍然可以滚动。
方案对比:
| 方案 | 优点 | 缺点 | 推荐 |
|---|---|---|---|
| body overflow:hidden | 简单 | iOS 12- 失效 | ⭐⭐ |
| body position:fixed | 彻底 | 页面跳到顶部 | ⭐⭐⭐ |
| touchmove.prevent | Vue 友好 | 仅 Vue | ⭐⭐ |
| overscroll-behavior | CSS 原生 | 兼容性一般 | ⭐⭐ |
| fixed + scrollTop 恢复 | 完美 | 稍复杂 | ⭐⭐⭐⭐⭐ |
推荐方案(完整代码):
js
// 打开蒙层
const scrollTop = document.documentElement.scrollTop;
document.body.style.cssText = `position:fixed;width:100%;top:-${scrollTop}px;`;
// 关闭蒙层
document.body.style.cssText = '';
window.scrollTo(0, scrollTop);图片预览组件(带缩放拖拽)
知识点:
- 缩放:
transform: scale(n),监听wheel事件(桌面)和双指touchstart(移动端) - 拖拽:
transform: translate(x, y)或left/top绝对定位 - 居中:
transform-origin: top left; left: 50%; top: 50%; transform: translate(-50%, -50%); dragover需e.preventDefault()才能触发drop事件- 移动端
touchmove需{ passive: false }否则无法调用preventDefault
获取鼠标/触摸位置
clientX / clientY— 相对视口pageX / pageY— 相对文档(含滚动)screenX / screenY— 相对屏幕offsetX / offsetY— 相对触发元素
拖拽场景用 clientX/Y,计算偏移量用 move.clientX - start.clientX。