完整的移動端開發(fā)筆記請戳https://github.com/zenglinan/Mobile-note
目錄:為了解決方案1(viewport適配)的缺點(無法對部分縮放储耐,部分不縮放)果元,出現(xiàn)了vw適配
流程
- 將設(shè)計稿(假設(shè)750px)上需要適配的尺寸轉(zhuǎn)換成vw,比如頁面元素字體標注的大小是32px邻悬,換成vw為 32/(750/100) vw
- 對于需要等比縮放的元素,CSS使用轉(zhuǎn)換后的單位
- 對于不需要縮放的元素省艳,比如邊框陰影瓜挽,使用固定單位px
(1) viewport設(shè)置 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
把layout viewport 寬度設(shè)置為設(shè)備寬度,不需要縮放
(2) 用js定義css的自定義屬性--width么库,表示每vw對應(yīng)的像素數(shù)傻丝。
(3) 根據(jù)設(shè)計稿標注設(shè)置樣式,比如標注稿里元素寬度為20px诉儒。這里設(shè)置 calc(20vw / var(--width))
// HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>viewport縮放實戰(zhàn)</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1">
<script>
const WIDTH = 750
document.documentElement.style.setProperty('--width', (WIDTH/100));
</script>
</head>
// CSS
header {
font-size: calc(28vw / var(--width));
}
優(yōu)點
可以對需要縮放的元素進行縮放葡缰,保留不需縮放的元素
缺點
書寫復(fù)雜,需要用calc計算
- 移動端click事件300ms延遲與解決方案
- 自己實現(xiàn)fastclick
1. 移動端click事件300ms延遲與解決方案
前置知識
移動端點擊監(jiān)聽執(zhí)行順序touchstart > touchmove > touchend > click
出現(xiàn)原因
iPhone是全觸屏手機的鼻祖,當(dāng)時的網(wǎng)頁都是為了大屏幕設(shè)備設(shè)置的(移動端沒有設(shè)置<meta name=""viewport>)泛释,
為了方便用戶閱讀滤愕,設(shè)定為用戶快速雙擊時,縮放頁面怜校。
當(dāng)用戶點擊第一下時间影,設(shè)備會等待300ms,若這300ms內(nèi)沒有再次點擊,才響應(yīng)click事件晦雨。
解決方案
- 設(shè)置
<meta name="viewport" content="width=device-width">
解決之后槽片,click事件仍會有些許延遲,那是因為click事件執(zhí)行順序在touchend之后随橘,正常延遲。 - 不使用click事件锦庸,改用touchstart事件
- 使用fastclick庫
2. 自己實現(xiàn)fastclick
fastclick是一個庫机蔗,用來解決移動端click事件300ms延遲。
使用
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body)
}, false)
原理
移動端在點擊第一下的時候會等待300ms甘萧,看用戶是否點擊第二下萝嘁。
fastclick的原理就是監(jiān)聽touchend事件,取消原本300ms后真正的click事件扬卷,自己生成分發(fā)一個點擊事件牙言。
簡單實現(xiàn)
const FastClick = !function(){
const attach = (dom) => {
let targetElement = null
dom.addEventListener('touchstart',function(e){
targetElement = e.target // 獲取點擊對象
})
dom.addEventListener('touchend',function(e){
e.preventDefault() // 阻止默認click事件
let touch = e.changeTouches[0] // 獲取點擊的位置坐標
let clickEvent = document.createEvent('MouseEvents')
// 初始化自定義事件
clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null)
targetElement.dispatchEvent(clickEvent) // 自定義事件的觸發(fā)
})
}
return {attach}
}()