在 Taro 中尺寸單位建議使用 px
、 百分比 %
,Taro 默認會對所有單位進行轉(zhuǎn)換。在 Taro 中書寫尺寸按照 1:1 的關(guān)系來進行書寫,即從設(shè)計稿上量的長度 100px
,那么尺寸書寫就是 100px
,當轉(zhuǎn)成微信小程序的時候,尺寸將默認轉(zhuǎn)換為 100rpx
,當轉(zhuǎn)成 H5 時將默認轉(zhuǎn)換為以 rem
為單位的值。
如果你希望部分 px
單位不被轉(zhuǎn)換成 rpx
或者 rem
,最簡單的做法就是在 px 單位中增加一個大寫字母,例如 Px
或者 PX
這樣,則會被轉(zhuǎn)換插件忽略。
結(jié)合過往的開發(fā)經(jīng)驗,Taro 默認以 750px
作為換算尺寸標準,如果設(shè)計稿不是以 750px
為標準,則需要在項目配置 config/index.js
中進行設(shè)置,例如設(shè)計稿尺寸是 640px
,則需要修改項目配置 config/index.js
中的 designWidth
配置為 640
:
const config = {
projectName: 'myProject',
date: '2018-4-18',
designWidth: 640,
....
}
目前 Taro 支持 750
、 640
、 828
三種尺寸設(shè)計稿,他們的換算規(guī)則如下:
const DEVICE_RATIO = {
'640': 2.34 / 2,
'750': 1,
'828': 1.81 / 2
}
建議使用 Taro 時,設(shè)計稿以 iPhone 6 750px
作為設(shè)計尺寸標準。
如果你的設(shè)計稿是 375
,不在以上三種之中,那么你需要把 designWidth
配置為 375
,同時在 DEVICE_RATIO
中添加換算規(guī)則如下:
const DEVICE_RATIO = {
'640': 2.34 / 2,
'750': 1,
'828': 1.81 / 2,
'375': 2 / 1
}
在編譯時,Taro 會幫你對樣式做尺寸轉(zhuǎn)換操作,但是如果是在 JS 中書寫了行內(nèi)樣式,那么編譯時就無法做替換了,針對這種情況,Taro 提供了 API Taro.pxTransform
來做運行時的尺寸轉(zhuǎn)換。
Taro.pxTransform(10) // 小程序:rpx,H5:rem
默認配置會對所有的 px
單位進行轉(zhuǎn)換,有大寫字母的 Px
或 PX
則會被忽略。
參數(shù)默認值如下:
{
onePxTransform: true,
unitPrecision: 5,
propList: ['*'],
selectorBlackList: [],
replace: true,
mediaQuery: false,
minPixelValue: 0
}
Type: Object | Null
設(shè)置 1px 是否需要被轉(zhuǎn)換
REM 單位允許的小數(shù)位。
允許轉(zhuǎn)換的屬性。
*
to enable all properties. Example: ['*']
*
at the start or end of a word. (['*position*']
will match background-position-y
)!
to not match a property. Example: ['*', '!letter-spacing']
['*', '!font*']
黑名單里的選擇器將會被忽略。
['body']
will match .body-class
[/^body$/]
will match body
but not .body
直接替換而不是追加一條進行覆蓋。
允許媒體查詢里的 px 單位轉(zhuǎn)換
設(shè)置一個可被轉(zhuǎn)換的最小 px 值
配置規(guī)則對應(yīng)到 config/index.js
,例如:
{
h5: {
publicPath: '/',
staticDirectory: 'static',
module: {
postcss: {
autoprefixer: {
enable: true
},
pxtransform: {
enable: true,
config: {
selectorBlackList: ['body']
}
}
}
}
},
weapp: {
// ...
module: {
postcss: {
pxtransform: {
enable: true,
config: {
selectorBlackList: ['body']
}
}
}
}
}
}
當前忽略單個屬性的最簡單的方法,就是 px 單位使用大寫字母。
/* `px` is converted to `rem` */
.convert {
font-size: 16px; // converted to 1rem
}
/* `Px` or `PX` is ignored by `postcss-pxtorem` but still accepted by browsers */
.ignore {
border: 1Px solid; // ignored
border-width: 2PX; // ignored
}
對于頭部包含注釋 /*postcss-pxtransform disable*/
的文件,插件不予處理。
更多建議: