我怎样才能得到windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX,screenY这将在所有主要浏览器中工作?
windowWidth
windowHeight
pageWidth
pageHeight
screenWidth
screenHeight
pageX
pageY
screenX
screenY
您可以使用 jQuery 获取窗口或文档的大小:
// Size of browser viewport. $(window).height(); $(window).width(); // Size of HTML document (same as pageHeight/pageWidth in screenshot). $(document).height(); $(document).width();
对于屏幕大小,您可以使用screen对象:
screen
window.screen.height; window.screen.width;
这有你需要知道的一切:获取视口/窗口大小
但简而言之:
var win = window, doc = document, docElem = doc.documentElement, body = doc.getElementsByTagName('body')[0], x = win.innerWidth || docElem.clientWidth || body.clientWidth, y = win.innerHeight|| docElem.clientHeight|| body.clientHeight; alert(x + ' × ' + y);
fiddle
以匹配他们的代码格式偏好。还指出,如果您只想针对现代浏览器,则不需要这样做 - 如果是这样,您只需要以下内容:
const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const height = window.innerHeight|| document.documentElement.clientHeight|| document.body.clientHeight; console.log(width, height);
(0,0)
pageX, pageY, screenX, screenY
screenHeight/Width
.availWidth/Height
windowWidth/Height
.clientWidth/Height
window.screenY
<body>
contentWidth
pageWidth/Height
pageX/Y
function sizes() { let contentWidth = [...document.body.children].reduce( (a, el) => Math.max(a, el.getBoundingClientRect().right), 0) - document.body.getBoundingClientRect().x; return { windowWidth: document.documentElement.clientWidth, windowHeight: document.documentElement.clientHeight, pageWidth: Math.min(document.body.scrollWidth, contentWidth), pageHeight: document.body.scrollHeight, screenWidth: window.screen.width, screenHeight: window.screen.height, pageX: document.body.getBoundingClientRect().x, pageY: document.body.getBoundingClientRect().y, screenX: -window.screenX, screenY: -window.screenY - (window.outerHeight-window.innerHeight), } } // TEST function show() { console.log(sizes()); } body { margin: 0 } .box { width: 3000px; height: 4000px; background: red; } <div class="box"> CAUTION: stackoverflow snippet gives wrong values for screenX-Y, but if you copy this code to your page directly the values will be right<br> <button onclick="show()" style="">CALC</button> </div>
我在 MacOs High Sierra 上的 Chrome 83.0、Safari 13.1、Firefox 77.0 和 Edge 83.0 上对其进行了测试