PHP与JavaScript获取screen.width/height及devicePixelRatio为何存在差异?
First, let's clarify a key point: screen.width, screen.height, and devicePixelRatio are all browser-provided device properties—they shouldn't depend on whether your JS is written directly in an HTML file or echoed via PHP. So the discrepancy you're seeing is almost certainly due to environmental differences in how the two pages are rendered, not the code generation method itself.
Let's walk through the most likely causes and fixes:
Accidental Browser Page Zoom
Your test results show the PHP case has adevicePixelRatioof ~1.0909 (which is 12/11), and the screen dimensions are scaled down proportionally (1920 → 1760, 1200 → 1100). This matches exactly what happens if you zoom the page to ~90.9% (10/11). Even if you thought you were using the same window, it's easy to accidentally hit Ctrl+Scroll or a zoom shortcut between loading the two pages.
Fix: Check the zoom level in your browser (Chrome: three-dot menu → Zoom; Firefox: three-line menu → Zoom) to ensure both pages are set to 100% zoom, then refresh and retest.Document Mode Differences
Your pure JS page lacks a<!DOCTYPE html>declaration, which forces browsers into "quirks mode" (an old compatibility mode for pre-HTML5 pages). If your PHP server automatically adds a DOCTYPE to responses (common in default Apache/Nginx configs), the PHP-output page will render in standard HTML5 mode. While modern browsers shouldn't alter screen properties based on document mode, older browsers (like IE) might have edge cases here.
Fix: Add<!DOCTYPE html>to the top of your pure JS page, then retest to ensure both pages use the same document mode.Browser Extension Interference
Some browser extensions (like privacy tools or screen resolution modifiers) can alter device properties for specific page types (e.g., only for server-hosted pages, not local files).
Fix: Disable all extensions temporarily, then reload both pages and test again.Incomplete Page Structure
Your PHP code only outputs three<script>tags, no<html>or<body>wrapper. Browsers will auto-generate these elements, but in rare cases, this incomplete structure might trigger automatic scaling or rendering quirks that affect how the browser reports device properties (though this is unlikely for screen-specific values).
Fix: Wrap your PHP-output JS in a full HTML structure (matching your pure JS page) and retest:<?php echo '<!DOCTYPE html><html><body>'; echo '<script>document.write(window.screen.width);</script> '; echo '<script>document.write(window.screen.height);</script> '; echo '<script>document.write(window.devicePixelRatio);</script>'; echo '</body></html>'; ?>
To recap: These device properties are determined by your system's display settings and browser state, not how the JS is served. The most probable fix is verifying your browser zoom level is consistent across both tests.
内容的提问来源于stack exchange,提问作者user3183784




