【uni-app】JS动态修改scss样式变量

需求:

1、 当H5嵌入到APP时,使用H5自身的头部,需要兼容手机自带的navbar高度,因此在嵌入APP时,需要固定H5 navbar距离手机自带头部高度:$uni-head:44px; 而paging-head-top是由于z-paging定位导致会覆盖或高度不适配当前navbar,所以设置88px

2、 当H5嵌入到H5时,类似于使用手机浏览器打开的页面,就不需要固定距离手机自带的头部高度。因此需要根据环境动态修改scss定义的变量。所以需要根据嵌入的环境进行判断并动态控制样式。即:H5嵌入APP需要固定距离手机顶部高度,H5嵌入H5不需要固定该高度。

未增加距离手机顶部高度时(左:H5嵌入APP)以及已增加距离手机顶部高度(右:H5嵌入H5)

方案一:

1、在scss文件中定义变量和默认值:如uni.scss

css 复制代码
$uni-head: var(--uni-head, 44px); // 默认值 44px
$paging-head-top: var(--paging-head-top, 88px); // 默认值 88px

2、js文件中业务判断并修改变量:main.js

js 复制代码
// 通过 User Agent中是否含有有Html5Plus、uni-app、app判断 嵌入到哪个环境中:
if (!uni.getSystemInfoSync().ua.includes('app')) { // 嵌入到h5
  document.getElementsByTagName('body')[0].style.setProperty('--uni-head', '0');
  document.getElementsByTagName('body')[0].style.setProperty('--paging-head-top', '44px');
}

// 或者通过 window.plus 判断: 
if(window.plus){ // 存在则是嵌入到APP

}else{ // 不存在则是其他环境 

}

结果展示:

H5嵌入APP(左:增加距离手机顶部高度44px);H5嵌入H5(右:未增加距离手机顶部高度)

方案二:可结合vuex进行动态修改

1、在Vuex store中定义对应样式变量

js 复制代码
// 在 Vuex store 中定义
const store = new Vuex.Store({
    state: {
        styleVars: {
            uniHeight: '44px', // 默认值
        },
    },
    mutations: {
        setStyleVar(state, { key, value }) {
            state.styleVars[key] = value;
        },
    },
});

2、在组件中使用计算属性绑定样式

html 复制代码
<template>
    <view :style="{ height: heightVar }">
        <!-- 组件内容 -->
    </view>
</template>

<script>
export default {
    computed: {
        heightVar() {
            return this.$store.state.styleVars.uniHeight;
        },
    },
};
</script>

多页面使用到该变量时可以将其定义成全局变量:main.js

js 复制代码
Vue.prototype.uniHeight = store.state.styleVars.uniHeight;
// 通过 User Agent中是否含有有Html5Plus、uni-app、app判断 嵌入到哪个环境中:
if (!uni.getSystemInfoSync().ua.includes('app')) { // 嵌入到h5
  // 更新全局样式变量
  Vue.prototype.$store.commit('setStyleVar', { key: 'uniHeight', value: '0px' });
}

组件中使用:

html 复制代码
<template>
    <view :style="{ height: uniHeight }">
        <!-- 组件内容 -->
    </view>
</template>

3、更新全局样式变量

js 复制代码
this.$store.commit('setStyleVar', { key: 'uniHeight', value: '0px' });
相关推荐
狗都不学爬虫_1 天前
JS逆向 -最新版 盼之(decode__1174、ssxmod_itna、ssxmod_itna2)纯算
javascript·爬虫·python·网络爬虫·wasm
天天进步20151 天前
透明的可观测性:剖析 Motia Workbench 与插件系统架构
javascript
夏河始溢1 天前
一八四、Zustand 状态管理详解、与 Redux、MobX 的对比分析
前端·javascript·react.js·状态管理·zustand
wangmengxxw1 天前
设计模式 -详解
开发语言·javascript·设计模式
Code小翊1 天前
TypeScript 核心语法速查
前端·javascript·typescript
家里有只小肥猫1 天前
uniApp下拉渐变头部 拿来即用
前端·javascript·uni-app
a1117761 天前
实验室预约管理系统(开源 FastAPI + Vue )
vue.js·开源·fastapi
我是伪码农1 天前
Vue 2.2
前端·javascript·vue.js
●VON1 天前
React Native for OpenHarmony:深入剖析 Switch 组件的状态绑定、无障碍与样式定制
javascript·学习·react native·react.js·von
时光追逐者1 天前
一个基于 .NET + Vue 实现的通用权限管理平台(RBAC模式),前后端分离模式,开箱即用!
前端·vue.js·c#·.net·.net core