前端大屏之vw vh

當(dāng)接到可視化大屏需求時,你是否會有以下疑問??如何做一款定制化的數(shù)據(jù)大屏? 開發(fā)可視化數(shù)據(jù)大屏如何做自適應(yīng)? vm vh、rem、scale 到底哪種比較好? 時間不夠,有沒有偷懶的方法?

實現(xiàn)方法:

css 方案 - sass

utils.scss

// 使用 scss 的 math 函數(shù),https://sass-lang.com/documentation/breaking-changes/slash-div
@use "sass:math";
 
// 默認(rèn)設(shè)計稿的寬度
$designWidth: 1920;
// 默認(rèn)設(shè)計稿的高度
$designHeight: 1080;
 
// px 轉(zhuǎn)為 vw 的函數(shù)
@function vw($px) {
  @return math.div($px, $designWidth) * 100vw;
}       
 
// px 轉(zhuǎn)為 vh 的函數(shù)
@function vh($px) {
  @return math.div($px, $designHeight) * 100vh;
}

路徑配置只需在vue.config.js里配置一下utils.scss的路徑,就可以全局使用了
vue.config.js

module.exports = {
    css: {
        loaderOptions: {
            scss: {
                prependData: `@import "@/assets/css/utils.scss";`
            }
        }
    },
}
//如果node版本比較高的話,api有會有變化
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  css: {
    loaderOptions: {
        scss: {
            additionalData: `@import "@/scss/utils.scss";`
        }
    }
}
  
})

在 .vue 中使用

<template>
    <div class="box">   
    </div>
</template>
 
<script>
export default{
    name: "Box",
}
</script>
 
<style lang="scss" scoped="scoped">
/* 
 直接使用 vw 和 vh 函數(shù),將像素值傳進(jìn)去,得到的就是具體的 vw vh 單位   
 */
.box{
    width: vw(300);
    height: vh(100);
    font-size: vh(16);
    background-color: black;
    margin-left: vw(10);
    margin-top: vh(10);
    border: vh(2) solid red;
}
</style>

css 方案 - less

utils.less
@charset "utf-8";
// 默認(rèn)設(shè)計稿的寬度
@designWidth: 1920;
// 默認(rèn)設(shè)計稿的高度
@designHeight: 1080;
 
.px2vw(@name, @px) {
  @{name}: (@px / @designWidth) * 100vw;
}
 
.px2vh(@name, @px) {
  @{name}: (@px / @designHeight) * 100vh;
}
 
.px2font(@px) {
  font-size: (@px / @designWidth) * 100vw;
}

路徑配置在vue.config.js里配置一下utils.less
<style lang="less" scoped="scoped">
/* 
 直接使用 vw 和 vh 函數(shù),將像素值傳進(jìn)去,得到的就是具體的 vw vh單位   
 */
.box{
    .px2vw(width, 300);
    .px2vh(height, 100);
    .px2font(16);
    .px2vw(margin-left, 300);
    .px2vh(margin-top, 100);
    background-color: black;
}
</style>

定義 js 樣式處理函數(shù)
// 定義設(shè)計稿的寬高
const designWidth = 1920;
const designHeight = 1080;
 
// px轉(zhuǎn)vw
export const px2vw = (_px) => {
  return (_px * 100.0) / designWidth + 'vw';
};
 
export const px2vh = (_px) => {
  return (_px * 100.0) / designHeight + 'vh';
};
 
export const px2font = (_px) => {
  return (_px * 100.0) / designWidth + 'vw';
};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容