你看到了吗
How to detect page zoom level in all modern browsers?
window.devicePixelRatio
window.screenX
和
window.screenY
考虑到这个因素:
var X = window.screenX * pixelratio;
var Y = window.screenY * pixelratio;
我在firefox48中测试了这一点,当改变缩放级别时,窗口位置最多改变了2个像素。使用
窗口设备像素比率
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<input id="button" type="button" value="Click me!"/>
<style id=binarysearch></style>
<div id=dummyElement>Dummy element to test media queries.</div>
<script>
var mediaQueryMatches = function(property, r) {
var style = document.getElementById('binarysearch');
var dummyElement = document.getElementById('dummyElement');
style.sheet.insertRule('@media (' + property + ':' + r +
') {#dummyElement ' +
'{text-decoration: underline} }', 0);
var matched = getComputedStyle(dummyElement, null).textDecoration
== 'underline';
style.sheet.deleteRule(0);
return matched;
};
var mediaQueryBinarySearch = function(
property, unit, a, b, maxIter, epsilon) {
var mid = (a + b)/2;
if (maxIter == 0 || b - a < epsilon) return mid;
if (mediaQueryMatches(property, mid + unit)) {
return mediaQueryBinarySearch(property, unit, mid, b, maxIter-1, epsilon);
} else {
return mediaQueryBinarySearch(property, unit, a, mid, maxIter-1, epsilon);
}
};
</script>
<script type="text/javascript">
var b = document.getElementById("button");
b.onclick = function() {
var pixelratio = mediaQueryBinarySearch(
'min--moz-device-pixel-ratio', '', 0, 6000, 25, .00001);
console.log("devicePixelRatio:", window.screenX * window.devicePixelRatio, window.screenY * window.devicePixelRatio);
console.log("binary search:", window.screenX * pixelratio, window.screenY * pixelratio);
console.log(Math.abs(pixelratio - window.devicePixelRatio));
}
</script>
</body>
</html>