1. 程式人生 > 其它 >H5頁面自定義 pxTorem 函式進行單位轉換

H5頁面自定義 pxTorem 函式進行單位轉換

一、css部分(mixin.scss):

$browser-default-font-size: 16px !default;

@function pxTorem($px) {

  //$px為需要轉換的字號
  @if (unitless($px)) {
    @return pxTorem($px + 0px);
  }

  @else if (unit($px)==em) {
    @return $px;
  }

  @return ($px / $browser-default-font-size) * 1rem;
}

二、js部分(main.js):

// 基準大小
const
baseSize = 32 // 設定 rem 函式 function setRem() { // 當前頁面寬度相對於 750 寬的縮放比例,可根據自己需要修改。 let scale = document.documentElement.clientWidth / 750 if (scale > 1) { scale = 1.024 } // 設定頁面根節點字型大小 document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px' } // 初始化
setRem() // 改變視窗大小時重新設定 rem window.onresize = function () { setRem() }

三、補充知識點:

1、sass-unitless() 函式

unitless() 函式相對來說簡單明瞭些,只是用來判斷一個值是否帶有單位,如果不帶單位返回的值為 true,帶單位返回的值為 false:

>> unitless(100)
true
>> unitless(100px)
false
>> unitless(100em)
false
>> unitless(100%)
false
>> unitless(1
/2 ) true >> unitless(1 /2 + 2 ) true >> unitless(1px /2 + 2 ) false

例如:

// 判斷如果沒有單位則加上單位"px"@mixin adjust-location($x, $y) {
  @if unitless($x) {    
    $x: 1px * $x;
  }
  @if unitless($y) {    
    $y: 1px * $y;
  }
  position: relative; 
  left: $x; 
  top: $y;
}

.botton{
    @include adjust-location(20px, 30);
}

2、sass-unit() 函式

unit() 函式主要是用來獲取一個值所使用的單位,碰到複雜的計算時,其能根據運算得到一個“多單位組合”的值,不過只充許乘、除運算:

>> unit(100)
""
>> unit(100px)
"px"
>> unit(20%)
"%"
>> unit(1em)
"em"
>> unit(10px * 3em)
"em*px"
>> unit(10px / 3em)
"px/em"
>> unit(10px * 2em / 3cm / 1rem)
"em/rem"

但加、減碰到不同單位時,unit() 函式將會報錯,除 px 與 cm、mm 運算之外

>> unit(1px + 1cm)
"px"
>> unit(1px - 1cm)
"px"
>> unit(1px + 1mm)
"px"
>> unit(10px * 2em - 3cm / 1rem)
SyntaxError: Incompatible units: 'cm' and 'px*em'.
>> unit(10px * 2em - 1px / 1rem)
SyntaxError: Incompatible units: '' and 'em'.
>> unit(1px - 1em)
SyntaxError: Incompatible units: 'em' and 'px'.
>> unit(1px - 1rem)
SyntaxError: Incompatible units: 'rem' and 'px'.
>> unit(1px - 1%)
SyntaxError: Incompatible units: '%' and 'px'.
>> unit(1cm + 1em)
SyntaxError: Incompatible units: 'em' and 'cm'.

unit() 函式對於單位運算相對來說也沒有規律,而且有些單位也無法整合成一個單位,對於我們在 CSS 中運用中並不適合,比如:

>> unit(10px * 3em)
"em*px"
>> unit(10px / 3em)
"px/em"
>> unit(10px * 2em / 3cm / 1rem)
"em/rem"

換句話說,上面運算出來的單位,對於在 CSS 中使用將是沒有任何意義的。