【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' });
相关推荐
大家的林语冰6 分钟前
✌️ 让 Rust 再次伟大,pnpm 12 抛弃 TypeScript,移植 Rust 原地起飞!
前端·javascript·node.js
名字还没想好☜2 小时前
React 用自定义 useDebounce Hook 治好搜索框频繁请求:防抖、竞态取消与卸载清理
前端·javascript·react.js·react·hooks
抓不住时间的沙2 小时前
butterfly主题美化,打造属于自己的个性博客
java·开发语言·前端·javascript·node.js·github
JavaDog程序狗3 小时前
【指南】uni-app微信小程序多环境CI-CD完全指南
ci/cd·uni-app·jenkins
PedroQue993 小时前
uni-router v2.1.0 升级:导航守卫全面支持返回值模式
前端·uni-app
嘟嘟07173 小时前
顺时针螺旋填充 n×n 矩阵:手撕 generateMatrix 的四个 for 循环
javascript·算法·面试
weixin_BYSJ19873 小时前
springboot技能与工具共享小程序---附源码29657
java·javascript·spring boot·python·小程序·django·php
张元清3 小时前
React useSessionStorage Hook:刷新不丢、只属于当前标签页的状态 (2026)
前端·javascript·react.js
weixin_BYSJ19873 小时前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
xiaominlaopodaren4 小时前
three.js最小地图运行时(一):视图状态
javascript·gis·three.js