function prasePxToCm(px)
{
var targetEleWidth=1,cm;
var createEle=document.createElement('input');
var body = document.getElementsByTagName("body");
createEle.setAttribute("style","width:1cm !important;height:1cm !important;border-width:0px !important;padding:0px !important;margin:0px !important;");
createEle.id="elementId_"+new Date().getTime();
createEle.type="hidden";
body[0].appendChild(createEle);
var targetEle=document.getElementById(createEle.id);
targetEleWidth=window.getComputedStyle(targetEle).width.match(/^\d+\.?\d*/)[0];
cm=px/targetEleWidth;
targetEle.parentNode.removeChild(targetEle);
return cm.toFixed(3);
}
- 参数px 是传递的像素数值
- 返回值是保留3位小数的cm数值
注意使用此方法document中应该要包含body元素,如果没有body元素可以将代码中
var body = document.getElementsByTagName("body");
中"body"替换为document中有的元素即可(但是想想DOM中怎么可能没有body元素呢)。