移动屏幕/视口大小检测-Javascript
我想报告移动设备的屏幕大小并更新方向变化,但我收到各种奇怪的错误,例如宽度几乎总是980px 在桌面上调整大小时,此功能可以正常工作,但在移动设备上无法正常工作(不过可以报告横向或纵向) 在ipad、三星galaxy tab、谷歌nexus手机和iPhone4上试用 以下是我正在使用的:移动屏幕/视口大小检测-Javascript,javascript,Javascript,我想报告移动设备的屏幕大小并更新方向变化,但我收到各种奇怪的错误,例如宽度几乎总是980px 在桌面上调整大小时,此功能可以正常工作,但在移动设备上无法正常工作(不过可以报告横向或纵向) 在ipad、三星galaxy tab、谷歌nexus手机和iPhone4上试用 以下是我正在使用的: // get dimensions _getScreenWidth = function() { var screenWidth = window.innerWidth; var screenHeigh
// get dimensions
_getScreenWidth = function() {
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var el = document.getElementById('dimensions');
_handleOrientation();
el.innerHTML = 'Width: '+screenWidth +' :: Height: '+screenHeight + "<br /><br />" + _doc_element.className;
};
// portait or landscape
_handleOrientation = function() {
if (device.landscape()) {
_removeClass("portrait");
return _addClass("landscape");
} else {
_removeClass("landscape");
return _addClass("portrait");
}
};
// resize event
var resizeTimeout;
window.onresize = function() {
clearTimeout(resizeTimeout);
// handle normal resize
resizeTimeout = setTimeout(function() {
_getScreenWidth();
}, 250); // 250ms delay
}
//获取维度
_getScreenWidth=函数(){
var screenWidth=window.innerWidth;
var screenHeight=window.innerHeight;
var el=document.getElementById('dimensions');
_handleOrientation();
el.innerHTML='Width:'+screenWidth+'::Height:'+screenHeight+“
”+\u doc\u element.className;
};
//还是景观
_handleOrientation=函数(){
if(device.landscape()){
_removeClass(“肖像”);
返回_addClass(“景观”);
}否则{
_removeClass(“景观”);
返回_addClass(“肖像”);
}
};
//调整事件大小
var-resizeTimeout;
window.onresize=函数(){
clearTimeout(resizeTimeout);
//句柄正常调整大小
resizeTimeout=setTimeout(函数(){
_getScreenWidth();
},250);//250毫秒延迟
}
您将无法获得物理像素的宽度。相反,您将收到“CSS像素”。这就是为什么你会出现奇怪的错误。对于方向检测,您可以使用“CSS像素”,只需比较宽度和高度。我不确定设备.scape()
应该是什么,但设备
对象不存在,至少在标准浏览器中不存在
各种奇怪的错误
在我的例子中,这是由于未定义的\u addClass
和\u removeClass
函数、\u doc\u element
对象以及如上所述的device.scape()
要修复设备.横向()
,可以将横向定义为宽度>高度的模式。那么这只是一个简单的比较:
isLandscape = function() {
return window.innerWidth > window.innerHeight;
}
下面是修复了所有错误的示例。在iPhone6上测试,设置了正确的类