寻求scss函数和媒体查询组合方案

如题:需求是小于1920px,vw函数直接返回px值,大于1920转换为vw,
这样做的目的是在页面中不需要写媒体查询的代码

$vw_base: 1920;/*设计稿基数*/
/*尝试将媒体查询融合到SCSS函数*/
@media screen and (min-width: 1920px) {
  @function vw($px) {
    @return ($px/$vw_base)*100vw
  }
}
@media screen and (max-width: 1920px) {
   @function vw($px) {
    @return $px
  }
}

页面中使用

.index-comp-ct {
  width: vw(1920);
  height: vw(1080);
  border: 1px solid;
  overflow: auto;
}

但是这样行不通,不知道是否有其他方案

阅读 4k
2 个回答

自问自答:
抛砖引玉
我的解决方式:自己搞个loader,处理样式

// vue.config.js
module.exports = {
  ...
  chainWebpack: config => {
    const cssRule = config.module.rule('vue')
    cssRule
      .use(require.resolve('./my-loader.js'))
      .loader(require.resolve('./my-loader.js'))
  },
 ...
}

loader:

// my-loader.js
const vwLine = /^\s*(\w+(?:-\w+)?):((\s*vw\(\d+\)){1,4})(\w)*\s*;$/mgi // 匹配 是否含有vw单位;
const vwValue = /vw\((\d+)\)/
function replaceFn (match) {
  return `@media screen and (min-width: 1920px) {
     ${match.trim()}
   }` + '\n' + `@media screen and (max-width: 1920px) {
     ${match.replace(vwValue, '$1px')}
   }`
}
module.exports = function(content) {
  content = content.replace(vwLine, replaceFn)
  this.callback(null, content)
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
            font-size: 0;
        }
        :root{
            --u: 10px;
        }
        @media screen and (max-width: 500px) {
            :root{
                --u:1px;
            }
        }
        @media screen and (min-width: 500px) {
            :root{
                --u:1vw;
            }
        }
        div{
            width: calc(20 * var(--u));
            background-color: red;
            height: 10px;
        }
    </style>
</head>
<body>
<div></div>
</body>
</html>

这样试试呢

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进