Skip to content

引入

ts
import {
  handleImgUnit,
  getHttpsUrl,
  tinyImage,
  isSupportedWebp,
  getCdnUrl,
  getCompressImgUrl
} from 't-comm';

// 不支持 tree-shaking 的项目
import {
  handleImgUnit,
  getHttpsUrl,
  tinyImage,
  isSupportedWebp,
  getCdnUrl,
  getCompressImgUrl
} from 't-comm/lib/image/index';

// 只支持 ESM 的项目
import {
  handleImgUnit,
  getHttpsUrl,
  tinyImage,
  isSupportedWebp,
  getCdnUrl,
  getCompressImgUrl
} from 't-comm/es/image/index';

handleImgUnit

描述

处理图片尺寸,即去掉单位 px/rem,将 string 类型转为 number 类型 rem 单位的话,会将数值乘以根元素的 fontSize,以获取对应的 px 值

参数

参数名类型描述
sizeNumber | String

输入单位

返回: Number

处理后的数值

示例

typescript
handleImgUnit(3)
// 3

handleImgUnit('10')
// 10

handleImgUnit('30px')
// 30

handleImgUnit('5rem')
// 250

document.documentElement.style.fontSize = '10px';
handleImgUnit('5rem')
// 50

getHttpsUrl

描述

将图片地址由 http 替换为 https 协议

参数

参数名描述
url

图片地址

返回:

新的地址

tinyImage

描述

压缩图片,会依次执行 getHttpsUrl, getCdnUrl, getCompressImgUrl

参数

参数名类型默认值描述
urlstring

图片地址

[imageWidth]number0

宽度

[imageHeight]number0

高度

返回:

新的 url 地址

isSupportedWebp

描述

判断当前浏览器是否支持 webp

参数

返回: Promise.<boolean>

是否支持

getCdnUrl(url)

描述

获取 cdn 链接

参数

参数名类型描述
urlstring

图片地址

返回:

新的地址

getCompressImgUrl(url, [imageWidth], [imageHeight])

描述

获取压缩后的图片

参数

参数名类型默认值描述
urlstring

图片地址

[imageWidth]number0

宽度

[imageHeight]number0

高度

返回:

新的 url 地址