美文网首页
从想看uni-grid的源码说起

从想看uni-grid的源码说起

作者: 小遁哥 | 来源:发表于2022-08-03 16:55 被阅读0次

    3 * 3 显示图片,间距为10像素。当时我想自己实现个正方形,时间紧、任务重,就借助了uni-gid;又想:nth-child(an+b)来给不同位置的图片设置样式,时间紧、任务重就:nth-child(1),:nth-child(4),:nth-child(7)...

    实现个正方形

            .parent-wrap {
                width: 200px;
            }
    
            .parent-wrap .square {
                float: left;
                width: calc(33.3% - 7px);
                padding-top: calc(33.3% - 7px);
                background-color: red;
                margin-bottom: 10px;
            }
    
            .parent-wrap .square:nth-child(3n-2),
            .parent-wrap .square:nth-child(3n-1) {
                margin-right: 10px;
            }
    
    
        <div class="parent-wrap">
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
        </div>
    
    preview.png

    padding-top: calc(33.3% - 7px);

    我当时以为是按照自身的宽度写的100%,实际上是按照父元素的宽度。 三个格子间距就按21算,每个格子宽度33% - 7px,所以和witdh元素保持一致即可。

    可以直接把.square 换成 img标签,padding-top换成height即可,而无需使用绝对定位的方式

    :nth-child(3n-2),:nth-child(3n-1)

    这里就用到高中数学知识了,元素的顺序是按照1开始的

    1 2 3
    4 5 6
    7 8 9

    但运用到an+b中,n是从0开始的,当时也以为是从1开始,还有...总之当时的脑子很乱。

    倒着推更省事,3、6、9 是 3n,那么2、5、8就是3n-1,1、4、7就是3n-2

    n为0时,3n-1是-1,3n-2是-2,都不会起作用。

    1 2 3 4
    5 6 7 8
    9 10 11 12

    规律就是4n、4n-1、4n-2、4n-3,以此类推。

    真是失之毫厘,差之千里,就如同自己一个人练习投篮和打比赛的区别,业务开发中干扰因素有很多,这时候基础再不扎实可能就死在第一步了,汗颜、汗颜。

    回到uni-grid的源码,本质上就是获取父元素的宽度然后均分给子元素,这有个弊端,那就是父元素一开始必须要有宽度,而不能由子元素撑开,而自己实现则灵活的多,比如借助vw。

            uni
              .createSelectorQuery()
              .in(this)
              .select(`#${this.elId}`)
              .boundingClientRect()
              .exec((ret) => {
                this.width = parseInt((ret[0].width - 1) / this.column) + "px";
                fn(this.width);
              });
            // #endif
            // #ifdef APP-NVUE
            dom.getComponentRect(this.$refs["uni-grid"], (ret) => {
              this.width = parseInt((ret.size.width - 1) / this.column) + "px";
              fn(this.width);
            });
            
    

    前端工程化文章推荐:

    对代码零入侵的 mock 解决方案,按项目、请求路径生成 js 文件,数据随意定制

    一键解析 swager 数据并生成简洁 UI,添加关注接口、生成 ajax 代码、枚举健值解析等功能

    超越封装极限,适用前端程序员的低代码平台,用程序记录你的操作,体验ast的实际应用

    相关文章

      网友评论

          本文标题:从想看uni-grid的源码说起

          本文链接:https://www.haomeiwen.com/subject/vxqewrtx.html