2011-04-20 82 views
97

在JavaScript中可以使用检测方向模式:如何使用CSS媒体查询检测设备方向?

if (window.innerHeight > window.innerWidth) { 
    portrait = true; 
} else { 
    portrait = false; 
} 

但是,有没有办法只使用CSS来检测取向?

例如,是这样的:

@media only screen and (width > height) { ... } 
+1

不错的想法与JS! – sshow 2014-01-06 14:46:21

回答

252

CSS来检测屏幕方向:

@media screen and (orientation:portrait) { … } 
@media screen and (orientation:landscape) { … } 

媒体查询的CSS定义是在http://www.w3.org/TR/css3-mediaqueries/#orientation

+1

很好地完成。应重新安装点数 – Martian2049 2016-07-05 08:19:20

+12

注意:此值与实际设备方向不符。在纵向打开大多数设备上的软键盘将导致视口变得比高度更宽,从而导致浏览器使用横向样式而不是纵向。 – 2017-03-10 08:58:32

+3

@JohannCombrink你提到这点非常重要。打开键盘会弄乱设计。好,你指出这一点。 – lowtechsun 2017-04-26 11:26:43

30
@media all and (orientation:portrait) { 
/* Style adjustments for portrait mode goes here */ 
} 

@media all and (orientation:landscape) { 
    /* Style adjustments for landscape mode goes here */ 
} 

,但它仍然看起来像你必须experiment

+1

方向取决于设备。某些平板电脑在横向模式下报告orientation = 0。 iPhone的报告与三星银河系不同。 – BlackMagic 2015-10-18 13:19:49

6

我认为我们需要编写更具体的媒体查询年。确保如果你写一个媒体查询它应该不会影响到其他视图(手机,标签,桌面),否则可能会有麻烦。我想建议为各个设备编写一个基本媒体查询,其中包含视图和一个方向媒体查询,您可以更详细地了解有关方向的代码,以便查看其良好实践。我们不需要同时写入两个媒体定位查询。你可以参考我的下面的例子。如果我的英语写作不太好,我很抱歉。 例如:

移动

@media screen and (max-width:767px) { 

..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view. 

} 


@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) { 


..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view. 

} 

对于平板

@media screen and (max-width:1024px){ 
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view. 
} 
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){ 

..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view. 

} 

桌面

使按您的设计要求享受...(:

感谢, 激凸

0

在Javascript中,最好是使用screen.widthscreen.height。这两个值在所有现代浏览器中都可用。即使浏览器在应用程序启动时被缩小,它们也会提供屏幕的真实尺寸。当浏览器缩小时,window.innerWidth会发生变化,这在移动设备上不会发生,但可能发生在PC和笔记本电脑上。

当移动设备在纵向和横向模式之间翻转时,screen.widthscreen.height的值会更改,因此可以通过比较这些值来确定模式。如果screen.width大于1280px,则您正在处理PC或笔记本电脑。

您可以在Javascript中构造一个事件侦听器来检测两个值的翻转时间。要专注的肖像screen.width值是320px(主要是iPhone),360px(大多数其他手机),768px(小型平板电脑)和800px(常规平板电脑)。