在不同的屏幕上获取每厘米 的像素值

255 阅读1分钟
// 获取每厘米的像素值
function getOneMmsPx(res) {
  // 创建一个1cm宽的元素插入到页面,然后坐等出结果
  if (!document.getElementById('cm')) {
    let div = document.createElement('div');
    div.id = 'cm';
    div.style.width = '1cm';
    document.querySelector('body').appendChild(div);
    // console.log('新增cm1');
  }
  // 原生方法获取浏览器对元素的计算值
  let cm1 = document.getElementById('cm').getBoundingClientRect();
  return cm1.width * res;
}
//10厘米转换为像素
getOneMmsPx(10);