获取当前屏幕每英寸的css像素宽度方法

86 阅读1分钟
function getDPI() {
    const arrDPI = new Array();
    if (window.screen.deviceXDPI != undefined) {
        //ie 9
        arrDPI[0] = window.screen.deviceXDPI;
        arrDPI[1] = window.screen.deviceYDPI;
    } else {
        // 设置屏幕盒子宽高为一英寸,然后获取css像素宽高
        //chrome firefox
        const tmpNode = document.createElement('DIV');
        tmpNode.style.cssText = 'width:1in;height:1in;position:absolute;left:-2in;top:-2in;z-index:99;visibility:hidden';
        document.body.appendChild(tmpNode);
        arrDPI[0] = parseInt(tmpNode.offsetWidth);
        arrDPI[1] = parseInt(tmpNode.offsetHeight);
        tmpNode.parentNode.removeChild(tmpNode);
    }
    return arrDPI;
}
console.log('dpi:' + getDPI());