uni-app如何用JS動態(tài)修改scss樣式變量
需求:
1、 當(dāng)H5嵌入到APP時,使用H5自身的頭部,需要兼容手機自帶的navbar高度,因此在嵌入APP時,需要固定H5 navbar距離手機自帶頭部高度:$uni-head:44px
; 而paging-head-top
是由于z-paging定位導(dǎo)致會覆蓋或高度不適配當(dāng)前navbar,所以設(shè)置88px
。
2、 當(dāng)H5嵌入到H5時,類似于使用手機瀏覽器打開的頁面,就不需要固定距離手機自帶的頭部高度。因此需要根據(jù)環(huán)境動態(tài)修改scss定義的變量。所以需要根據(jù)嵌入的環(huán)境進行判斷并動態(tài)控制樣式。即:H5嵌入APP需要固定距離手機頂部高度,H5嵌入H5不需要固定該高度。
未增加距離手機頂部高度時(左:H5嵌入APP)以及已增加距離手機頂部高度(右:H5嵌入H5)
方案一:
1、在scss文件中定義變量和默認(rèn)值:如uni.scss
$uni-head: var(--uni-head, 44px); // 默認(rèn)值 44px $paging-head-top: var(--paging-head-top, 88px); // 默認(rèn)值 88px
2、js文件中業(yè)務(wù)判斷并修改變量:main.js
// 通過 User Agent中是否含有有Html5Plus、uni-app、app判斷 嵌入到哪個環(huán)境中: 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{ // 不存在則是其他環(huán)境 }
結(jié)果展示:
H5嵌入APP(左:增加距離手機頂部高度44px);H5嵌入H5(右:未增加距離手機頂部高度)
方案二:可結(jié)合vuex進行動態(tài)修改
1、在Vuex store中定義對應(yīng)樣式變量
// 在 Vuex store 中定義 const store = new Vuex.Store({ state: { styleVars: { uniHeight: '44px', // 默認(rèn)值 }, }, mutations: { setStyleVar(state, { key, value }) { state.styleVars[key] = value; }, }, });
2、在組件中使用計算屬性綁定樣式
<template> <view :style="{ height: heightVar }"> <!-- 組件內(nèi)容 --> </view> </template> <script> export default { computed: { heightVar() { return this.$store.state.styleVars.uniHeight; }, }, }; </script>
多頁面使用到該變量時可以將其定義成全局變量:main.js
Vue.prototype.uniHeight = store.state.styleVars.uniHeight; // 通過 User Agent中是否含有有Html5Plus、uni-app、app判斷 嵌入到哪個環(huán)境中: if (!uni.getSystemInfoSync().ua.includes('app')) { // 嵌入到h5 // 更新全局樣式變量 Vue.prototype.$store.commit('setStyleVar', { key: 'uniHeight', value: '0px' }); }
組件中使用:
<template> <view :style="{ height: uniHeight }"> <!-- 組件內(nèi)容 --> </view> </template>
3、更新全局樣式變量
this.$store.commit('setStyleVar', { key: 'uniHeight', value: '0px' });
總結(jié)
到此這篇關(guān)于uni-app用JS動態(tài)修改scss樣式變量的文章就介紹到這了,更多相關(guān)JS動態(tài)修改scss樣式變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ES6中Array.find()和findIndex()函數(shù)的用法詳解
ES6為Array增加了find(),findIndex函數(shù)。find()函數(shù)用來查找目標(biāo)元素,找到就返回該元素,找不到返回undefined,而findIndex()函數(shù)也是查找目標(biāo)元素,找到就返回元素的位置,找不到就返回-1。下面通過實例詳解,需要的朋友參考下吧2017-09-09javascript讀寫XML實現(xiàn)廣告輪換(兼容IE、FF)
最近更新網(wǎng)站首頁廣告,ASP.NET的廣告控件很容易實現(xiàn)這點,可首頁是靜態(tài)頁面,聯(lián)想廣告控件的原理決定采用javascript+xml實現(xiàn)這點方面配置,更新廣告時只要更新xml即可,方便了廣告輪換2013-08-08