我已经努力工作了几天,试图为Iphone 5 Safari浏览器方向检测编写JavaScript代码。一旦网页的用户将Iphone旋转到横向视图,该代码就可以成功进行初始检测。但是,它无法进行后续检测。我有链接到主asp页面和重定向的html消息页面的代码。花费了无数时间在Iphone 5上为Safari浏览器编写可行代码的人可以给我一些建议吗?谢谢!!!
此代码的目的是防止网页用户以横向模式查看网页。
这是JavaScript代码:
var matchMedia = window.msMatchMedia || window.MozMatchMedia || window.WebkitMatchMedia || window.matchMedia;
if (typeof (matchMedia) !== 'undefined') {
// use matchMedia function to detect orientationchange
window.matchMedia('(orientation: portrait)').addListener(function () {
window.location.href = "/handheld.aspx";
});
} else {
// use orientationchange event with timeout (don't know orientation. fires too early.)
$(window).on('orientationchange', function () {
window.setTimeout(function () {
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
//window.alert(window.orientation);
window.location.href = "/handheld.aspx";
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
//window.alert(window.orientation);
window.location.href = "/handheld/landscape.htm";
}
if (window.innerWidth > window.innerHeight) {
//alert('landscape');
window.location.href = "/handheld/landscape.htm";
} else {
//alert('portrait');
window.location.href = "/handheld.aspx";
}
}, 300)
});
}
window.addEventListener("resize", function () {
// Announce the new orientation number
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
//window.alert(window.orientation);
window.location.href = "/handheld.aspx";
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
//window.alert(window.orientation);
window.location.href = "/handheld/landscape.htm";
}
if (window.innerWidth > window.innerHeight) {
//alert('landscape');
window.location.href = "/handheld/landscape.htm";
} else {
//alert('portrait');
window.location.href = "/handheld.aspx";
}
}, false);