我意识到在获取设备尺寸等方面之前已经提出了类似的问题,但似乎对于确切的方法存在分歧。
假设我有
的媒体查询(例如Twitter Bootstrap)超小型设备电话(< 768px)
小型设备平板电脑(≥768px)
中型设备桌面(≥992px)
大型设备桌面(≥1200px)
现在,我希望能够使用Javascript基本上获得相同的输出。换句话说,css媒体查询像素数而不是实际的网点。也就是说,我不需要得到确切的答案,但是我想避免因为我得到的屏幕点而错过了2或3。而不是css像素。
我更关注移动设备 - 尤其是Android - 而不是桌面设备。 screen.width
可靠吗?或jQuery(document).width()
?
(这是针对一个研究项目,虽然我知道基本上不可能检测到平板电脑与手机,但我想知道人们正在使用的设备大小用户体验不会受到结果的影响。)
答案 0 :(得分:2)
我最喜欢这样做的方法如下(jQuery):
var viewportWidth = $(window).width();
// Then create if statements and execute code accordingly...
if (viewportWidth <= 767) {
// execute code
} else if (viewportWidth >= 768) {
// execute this
}
您还可以在宽度之间执行视口代码,例如:
if (viewportWidth >= 768 && viewportWidth <= 991) {
//execute this
}
当视口介于768px和991px之间时,这将执行代码......
答案 1 :(得分:1)
你可以使用像这样的Javascript获得窗口宽度
var wid = window.innerWidth;
超小型设备电话(&lt; 768px)
if (wid < 767) {
//execute this
}
小型设备平板电脑(≥768px)
if (wid >= 768 && wid <= 991) {
//execute this
}
中型设备台式机(≥992px)
if (wid >= 992 && wid <= 1199) {
//execute this
}
大型设备台式机(≥1200px)
if (wid >= 1200) {
//execute this
}
答案 2 :(得分:0)
这是我一直使用的脚本:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
然后,您可以将其调用为变量,并读取其高度和宽度属性:
var vp = viewport();
var vpWidth = vp.width;
var vpHeight = vp.height;