有没有适用于所有浏览器的方法?
原始回答
是的。
window.screen.availHeight
window.screen.availWidth
更新2017-11-10
来自Tsunamis在评论中的内容:
为了获得移动设备的本机分辨率,您需要乘以设备像素比:
window.screen.width * window.devicePixelRatio
和window.screen.height * window.devicePixelRatio
。这也适用于桌面设备,它们的比例是1。
还有来自Ben在另一个答案中的内容:
使用vanilla JavaScript,这将为您提供可用的宽度/高度:
window.screen.availHeight window.screen.availWidth
对于绝对宽度/高度,请使用:
window.screen.height window.screen.width
var width = screen.width;
var height = screen.height;
window.screen
。只需将其添加到现有答案中即可。 - Gajusscreen.availHeight
只提供了浏览器窗口中可用的高度,而screen.height
则提供了屏幕的确切高度。 - apnervewindow.screen.width * window.devicePixelRatio
和 window.screen.height * window.devicePixelRatio
。这个公式同样适用于桌面设备,其比值为1。 - Tsunamis在纯JavaScript中,这将为您提供可用的宽度/高度:
window.screen.availHeight
window.screen.availWidth
使用以下代码来设置元素的绝对宽度/高度:
```css width: 绝对值; height: 绝对值; ```window.screen.height
window.screen.width
以上两种写法都可以不用添加window前缀。
像jQuery?它可以在所有浏览器中工作,但每个浏览器给出的值可能不同。
$(window).width()
$(window).height()
window.innerWidth
和 window.innerHeight
属性。请参见 w3schools。您是指显示分辨率(例如每英寸72个点)还是像素尺寸(浏览器窗口当前为1000 x 800像素)?
屏幕分辨率可以让您知道10个像素线在英寸中的厚度。像素尺寸告诉您一条水平线占用可用屏幕高度的百分比,该线宽度为10个像素。
由于计算机本身通常不知道屏幕的实际尺寸,只知道像素数量,因此无法仅通过Javascript了解显示分辨率。 72 dpi是通常的猜测值......
请注意,关于显示分辨率有很多混淆,人们经常使用该术语代替像素分辨率,但两者是完全不同的。请参见维基百科
当然,您也可以以每厘米的点数来衡量分辨率。还有非正方形点的晦涩主题。但我岔开了话题。
$(window).width()
$(window).height()
尝试在移动设备上实现这一点需要更多的步骤。screen.availWidth
无论设备的方向如何,都保持不变。
这是我为移动设备提供的解决方案:
function getOrientation(){
return Math.abs(window.orientation) - 90 == 0 ? "landscape" : "portrait";
};
function getMobileWidth(){
return getOrientation() == "landscape" ? screen.availHeight : screen.availWidth;
};
function getMobileHeight(){
return getOrientation() == "landscape" ? screen.availWidth : screen.availHeight;
};
window.orientation
返回未定义...(Firefox 49) screen.orientation.angle
返回一个角度,但在横向模式下已经为0。 - Lambartfunction getScreenWidth()
{
var de = document.body.parentNode;
var db = document.body;
if(window.opera)return db.clientWidth;
if (document.compatMode=='CSS1Compat') return de.clientWidth;
else return db.clientWidth;
}
仅供将来参考:
function getscreenresolution()
{
window.alert("Your screen resolution is: " + screen.height + 'x' + screen.width);
}
$(window).width()
,参见chaim.dev的答案。 - BornToCodewindow.devicePixelRatio
。请参考我在Alessandro回答下的评论。 - Tsunamis