融合响应式布局

2020-08-28  本文已影响0人  陌客百里

*【序】 我们常用的响应式布局有flex,%,vw,vh,float,媒体查询等属性,也可以使用js来进行判断,怎么样将他们更好的融合以符合最优原则呢?原文链接

问题一

问题二

  1. PC,mobile
    在pc,mobile端展示网页内容


    PC,mobile
  2. ipad
    早期我们将ipad归为mobile类,但是技术发展,现在的ipad拥有了更高的像素,因此也单归类
    左图是ipad Pro展示移动端的样式,右图是ipad mini展示PC端的样式


    ipad

    因此,我们不能单纯的简单区分为PC与mobile

问题三

区分 Mobile UI 和 PC UI 的完整的判断逻辑如下:

笔记本电脑,不支持 onorientationchange 横竖屏切换的,就认定为 PC

不使用 onRisize 来监听网页的宽高,因为性能消耗大
并且当浏览器拖动小了,支持左右滚动
进入页面时,竖屏时以 window.innerWidth, window.innerHeight 中数值小的那个来判断,横屏中以 window.innerWidth, window.innerHeight 数值大的来判断,当宽度大于 1040px 时认为是 PC ,宽度小于 1040px 时,认定为 Mobile 。

横竖屏切换时,重复第 2 步的判断

备注:

window.innerWidth, window.innerHeight 在安卓和 iOS 上的横竖屏切换上有不一致的地方,所以以最大值或最小值来做更准确。

源码

import React from 'react' 
// JavaScript 的媒体查询 
const mqlMedia = window.matchMedia('(orientation: portrait)')

function onMatchMediaChange(mql = window.matchMedia('(orientation: portrait)')) { 
  if (mql.matches) { 
    //竖屏 
    return 'portrait' 
  } else { 
    //横屏 
    return 'horizontal' 
  } 
} 
// 输出当前屏幕模式 
const getUiMode = (uiMode = '', mql) => { 
  if (uiMode) return uiMode 
  if (!('onorientationchange' in window)) return 'pc' 
  let status = onMatchMediaChange(mql) 
  let width = status === 'portrait' ? Math.min(window.innerWidth, window.innerHeight) : Math.max(window.innerWidth, window.innerHeight) 
  if (width > 1040) return 'pc' 
  return 'mobile' 
} 
const getIsPcMode = (uiMode) => uiMode === 'pc' 
/** 
 * UI 模式,判断逻辑 
 * @export 
 * @param {*} Cmp 
 * @returns 
 */ 
export function withUiMode(Cmp, options = {}) { 
  return class WithUIRem extends React.Component { 
    constructor(props) { 
      super(props) 
      let uiMode = getUiMode() 
      let isPCMode = getIsPcMode(uiMode) 
      this.state = { 
        uiMode: uiMode, 
        isPCMode: isPCMode, 
      } 
    } 
    // 横竖屏切换监听 
    componentDidMount() { 
      mqlMedia.addListener(this.changeUiMode) 
    } 
    componentWillUnmount() { 
      mqlMedia.removeListener(this.changeUiMode) 
    } 
    changeUiMode = (mql) => { 
      let newUiMode = getUiMode('', mql) 
      if (newUiMode !== this.state.uiMode) { 
        this.setState({ 
          isPCMode: getIsPcMode(newUiMode), 
          uiMode: newUiMode 
        }) 
      } 
    } 
    render() { 
      return <Cmp {...this.state} {...this.props} /> 
    } 
  } 
} 
export default (options) => { 
  return (Cmp) =>  withUiMode(Cmp, options) 
}

问题四

  1. 我们能够根据不同的设备判断整体的布局,例如侧边栏是在顶部还是在侧边展示
  2. 在css中的媒体查询使得我们能够通过设备最大的宽度来精准的px更精确

问题五


总结

融合响应式设计( Fusion Web Design,简称 FWD),利用 JavaScript 和 CSS 来进行媒体查询,是响应式设计与自适应设计结合的方案。

上一篇 下一篇

猜你喜欢

热点阅读