• grunt写一个px和rem互转的工具


     

     

     

    在移动端使用REM单位来实现弹性布局已经非常普遍了,但是在书写css(or less、sass等)还是非常麻烦,要定义一个html的font-size,然后再定义元素的时候转换成rem书写。比如在640下root的font-size是20px,要应以一个宽度为100px的div.className,就要这样写:

    CSS

    @media only screen and (max- 640px), only screen and (max-device-640px) { html{ font-size:20px; } } .className{ 5rem;//5*20=100px }

    虽然可以定义一个容易计算的root font-size,但写起来还是太麻烦,并且一些用px布局的页面想要升级成rem的弹性页面,要手动一个个重写,所以干脆写个grunt脚本帮我们自动处理这件事情。

    https://github.com/leon776/grunt-px2rem

    安装以后稍微配置一下gruntfile

    javascript grunt.initConfig({ px2rem{ default: { options: { designWidth : 640, //设计稿宽度 baseFont : 20, //基础字体,在设计稿宽度下你要使用的root字体大小(随便填填) border : 1, //1不处理border,0处理 ie8 : 1, //1生成ie8代码,0不生成 dest : 'assets/css/' //rem css输出目录 mode : 0, //0:px转rem,1rem转px media : 1 //是否自动生成meadia query代码 }, files: [{ src : ['assets/css/*.css']//要监听的css目录 }] } } })

    还可以配置一下watch,自动监听文件的改变

    JAVASCRIPT watch: { css: { files: ['test/assets/css/*.css', 'tasks/px2rem.js'], tasks: ['px2rem'] } }

    然后就可以愉快的写css了:

    CSS

    .test{ 5px;height: 2px;} .test-shorthand{padding:20px 10px 30px 20px;} .test-border{border:1px solid #fff;border-radius:5px;} .test-other-unit{100%;padding:1px 1rem 1px 1%;} .test-single-line{ 5px;height: 2px;}.test-single-line{padding:20px 10px 30px 20px;} .test-no-semicolon{1px} .test-no-trans{font-size:12px/*except*/;}

    运行一下task,或者自动watch,就会生成下面的代码:

    CSS

    .test{ 0.25rem;height: 0.1rem;} .test-shorthand{padding:1rem 0.5rem 1.5rem 1rem;} .test-border{border:0.05rem solid #fff;border-radius:0.25rem;} .test-other-unit{100%;padding:0.05rem 1rem 0.05rem 1%;} .test-single-line{ 0.25rem;height: 0.1rem;}.test-single-line{padding:1rem 0.5rem 1.5rem 1rem;} .test-no-semicolon{0.05rem;} .test-no-trans{font-size:12px/*except*/;}

    说明:

    * px后面带/*except*/就不会被转换

    * 生成兼容ie8-的代码会是这个样子:

    .test{ 5px; 0.25rem;height: 2px;height: 0.1rem;}

    * media为1的话会自动生成以下代码,如果你用js计算html字体大小的话这个就不用了

    CSS

    @media only screen and (max- 1080px), only screen and (max-device-1080px) { html,body { font-size:33.75px; } } @media only screen and (max- 960px), only screen and (max-device-960px) { html,body { font-size:30px; } }<code> 等等等等</code>

    同时提供了gui和html版本给不喜欢grunt的同学

    还有在线版:

    http://mxd.tencent.com/wp-content/uploads/2014/11/rem.html

  • 相关阅读:
    关于VS下的应用程序出现0xc000007b的问题以及OpenCV相关的0xc000007b问题
    彻底解决DZ大附件上传问题
    基于Red5的视频直播平台
    .htaccess重写URL讲解
    了解Linux实时内核
    Linux操作系统实时性分析
    5分钟教程:如何通过UART获得root权限
    记一次有惊无险的Linux数据恢复过程
    11款最棒的Linux数据恢复工具
    Xamarin.Android开发实践(六)
  • 原文地址:https://www.cnblogs.com/qingqinglanlan/p/7565495.html
Copyright © 2020-2023  润新知