1.首先,單獨的響應式布局hold不住這個問題,因為出問題的是device-pixel-ratio。
2.問題現象是高分屏下整好的東西,在普分屏下會放大;而普分屏下整好的東西,在高分屏上會縮小。
3.重現這個問題不需要高分屏,直接用Ctrl++或者Ctrl+-出來的效果是跟高分屏一致的(所以搞定這個問題之后,也可以同時預防用戶誤觸網頁縮放)。另外恢復是Ctrl+Num0
4.解決的關鍵就是你得在媒體適配里寫device-pixel-ratio單獨適配像素比;另外,需要把絕大多數組件由px單位轉換為rem單位,因為需要在前邊提到的device-pixel-ratio里調節:root的font-size,以達到動態縮放的目的
5.(加上兼容)寫好以后的代碼類似:
@mediaalland (-moz-min-device-pixel-ratio:1.09) and (-moz-max-device-pixel-ratio:1.18), (-webkit-min-device-pixel-ratio:1.09) and (-webkit-max-device-pixel-ratio:1.18), (min-resolution:1.09dppx) and (max-resolution:1.18dppx) {:root{font-size:14px; }}@mediaalland (-moz-min-device-pixel-ratio:1.19) and (-moz-max-device-pixel-ratio:1.28), (-webkit-min-device-pixel-ratio:1.19) and (-webkit-max-device-pixel-ratio:1.28), (min-resolution:1.19dppx) and (max-resolution:1.28dppx) {:root{font-size:13px; }}@mediaalland (-moz-min-device-pixel-ratio:1.29) and (-moz-max-device-pixel-ratio:1.4), (-webkit-min-device-pixel-ratio:1.29) and (-webkit-max-device-pixel-ratio:1.4), (min-resolution:1.29dppx) and (max-resolution:1.4dppx) {:root{font-size:12px; }}@mediaalland (-moz-min-device-pixel-ratio:1.41) and (-moz-max-device-pixel-ratio:1.6), (-webkit-min-device-pixel-ratio:1.41) and (-webkit-max-device-pixel-ratio:1.6), (min-resolution:1.41dppx) and (max-resolution:1.6dppx) {:root{font-size:10px; }}@mediaalland (-moz-min-device-pixel-ratio:1.61) and (-moz-max-device-pixel-ratio:1.8), (-webkit-min-device-pixel-ratio:1.61) and (-webkit-max-device-pixel-ratio:1.8), (min-resolution:1.61dppx) and (max-resolution:1.8dppx) {:root{font-size:9px; }}@mediaalland (-moz-min-device-pixel-ratio:1.81) and (-moz-max-device-pixel-ratio:2.1), (-webkit-min-device-pixel-ratio:1.81) and (-webkit-max-device-pixel-ratio:2.1), (min-resolution:1.81dppx) and (max-resolution:2.1dppx) {:root{font-size:8px; }}
第二種js獲取
const detectZoom = () => {
? let ratio = 0,
? ? screen = window.screen,
? ? ua = navigator.userAgent.toLowerCase()
? if (window.devicePixelRatio !== undefined) {
? ? ratio = window.devicePixelRatio
? } else if (~ua.indexOf('msie')) {
? ? if (screen.deviceXDPI && screen.logicalXDPI) {
? ? ? ratio = screen.deviceXDPI / screen.logicalXDPI
? ? }
? } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
? ? ratio = window.outerWidth / window.innerWidth
? }
? if (ratio) {
? ? ratio = Math.round(ratio * 100)
? }
? return ratio
}
export { detectZoom as default, detectZoom }