V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
larryzhu9952
V2EX  ›  分享创造

推荐一个前端自适应插件,很简单但很好用

  •  
  •   larryzhu9952 · 56 天前 · 801 次点击
    这是一个创建于 56 天前的主题,其中的信息可能已经有所发展或是发生改变。

    autofit

    autofit.js

    迄今为止最易用的自适应工具

    理论上可以支持从你的设计稿以下的分辨率,只需一行代码。

    autofit.js 是一个可以让你的 PC 项目自适应屏幕的工具,其原理非常简单,即在 scale 等比缩放的基础上,向右或向下增加了宽度或高度,以达到充满全屏的效果,使用 autofit.js 不会挤压、拉伸元素,它只是单纯的设置了容器的宽高。

    引入

    import autofit from 'autofit.js'
    

    快速开始

    autofit.init()
    

    使用

    export default {  
      mounted() {
    	autofit.init({
            dh: 1080,
            dw: 1920,
            el:"body",
            resize: true
        })
      },
    }
    

    以上使用的是默认参数,可根据实际情况调整,可选参数有

       * - el:渲染的 dom ,默认是 "body",必须使用 id 选择器 
       * - dw:设计稿的宽度,默认是 1920 
       * - dh:设计稿的高度,默认是 1080
       * - resize:是否监听 resize 事件,默认是 true
       * - ignore:忽略缩放的元素(该元素将反向缩放),参数见 readme.md
       * - transition:过渡时间,默认是 0
       * - delay:默认是 0
       * - limit:默认是 0.1,当缩放阈值不大于此值时不缩放,比如设置为 0.1 时,0.9-1.1 的范围会被重置为 1
    

    忽略某些元素

    autofit.init({
      ignore: [
         { 
          el: ".gaodeMap",
         },
      ]
    })
    

    传入 ignore 以使元素不被缩放

    更个性化的设置:

    autofit.init({
      ignore: [
        {
          el: ".gaodeMap", //必填
          height: "300px",//可选,需注明单位
          width: "80%",//可选,需注明单位
          scale:1.2, //可选:回放程度,基于主元素缩放后的大小
          fontSize:26 //可选,如果自定义缩放后文字大小不合适,可以在这里设置文字大小
        },
        {
            //...
        }
      ]
    })
    

    如果反向缩放后的元素大小使结构发生变化,你还可以手动传入宽高、回放程度。

    ignore 还支持传入字符串数组:

    autofit.init({
      ignore: ['.gaodeMap','.leaflet','#someElementClassOrId']
    })
    

    elRectification

    一些 canvas 渲染的图表也会有事件偏移,而图表不同于地图,当使用 ignore 时,过大的图表可能会显示不全,因此可以使用elRectification (性能上不如 ignore )

    如果 ignore 无法满足需求,可以使用 autofit.elRectification(".classNameOrId")

    import { elRectification } from 'autofit.js'
    
    <div class="G2plot"></div>
    <div class="G2plot"></div>
    <div class="G2plot"></div>
    
    onMounted(() => {
      elRectification(".G2plot")
    })
    

    使用 elRectification 时,需要被矫正的元素已经挂载

    关闭 autofit.js 造成的影响

    当 autofit 未初始化时,会出现无法找到元素的错误,在使用 autofit.off()前,请确保已初始化。

    autofit.off()
    

    github:https://github.com/LarryZhu-dev/autofit.js

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2741 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 15:40 · PVG 23:40 · LAX 08:40 · JFK 11:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.