尝试了在SO上发现的大量不同选项,包括jQuery移动解决方案(导致与其他jQuery发生大量冲突),我发现以下代码会检测到屏幕旋转,我可以使用它来添加类。
$(window).bind("resize", function(){
screenOrientation = ($(window).height() > $(window).width())? 90 : 0;
$('.centerBoxContentsSubCat').addClass('mobile_landscape');
});
但是,我需要以相反的方式旋转.removeClass。
我尝试复制代码,切换高度和宽度的位置,但这没有用。 我尝试将代码更改为
$(window).bind("resize", function(){
if(screenOrientation = ($(window).height() > $(window).width())? 90 : 0){
$('.centerBoxContentsSubCat').addClass('mobile_landscape');
}else{
$('.centerBoxContentsSubCat').removeClass('mobile_landscape');
}
});
但这也不起作用。
我实际上是在为css使用@media查询,但是我需要在屏幕旋转时强制更改列数,并且所有其他尝试都无法得到甚至关闭。
关于我在哪里出错的任何建议?
答案 0 :(得分:1)
有两种不同的方法可以解决这个问题。
第一个是事件方向改变。
// Listen for orientation changes
window.addEventListener("orientationchange", function() {
// Announce the new orientation number
alert(window.orientation);
}, false);
第二个是matchMedia。
// Find matches
var mql = window.matchMedia("(orientation: portrait)");
// If there are matches, we're in portrait
if(mql.matches) {
// Portrait orientation
} else {
// Landscape orientation
}
// Add a media query change listener
mql.addListener(function(m) {
if(m.matches) {
// Changed to portrait
}
else {
// Changed to landscape
}
});
来源: http://davidwalsh.name/orientation-change
如果您需要支持旧浏览器,我建议使用此库:
答案 1 :(得分:0)
您需要使用orientationchange
事件,而不是调整大小。