下面是编程之家 jb51.cc 通过网络收集整理的代码片段。编程之家小编现在分享给大家,也给大家做个参考。
很多时候,为了让手机版横竖屏时有一个理想的效果,我们都需要通过判断区间来设定相应的 css 样式,现在的 CSS3 推出了一个可以判断手机横竖屏的媒体查询。在做移动端页面的时候经常会遇到需要判断横屏还是竖屏,下面将目前已知的通过 HTML,CSS,JS 三种判断方法记录下来,方便以后翻阅。
1、通过在 html 中分别引用横屏和竖屏的样式:
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow" > //引用竖屏的CSS
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow" > //引用横屏的CSS
@media (orientation: portrait ){
//竖屏CSS
}
@media ( orientation: landscape ){
//横屏CSS
}
3、js 判断是否为横屏竖屏:
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize",function() {
if (window.orientation === 180 || window.orientation === 0) {
alert('竖屏状态!');
}
if (window.orientation === 90 || window.orientation === -90 ){
alert('横屏状态!');
}
},false);
只要用户改变了设备的查看模式,就会触发 onorientationchange 事件。
orientation 有 4 个值:0,90,-90,180
值为 0 和 180 的时候为竖屏(180 为倒过来的竖屏);
90 和-90 时为横屏(-90 为倒过来的竖屏模式);
在 ipad、iphone 网页开发中,我们很可能需要判断是横屏或者竖屏。Android 和 IOS 刚好相反,下面介绍如何用 jQuery 判断 iPad、iPhone、Android 是横屏还是竖屏的方法
function orient() {
if (window.orientation == 90 || window.orientation == -90) {
//ipad、iphone竖屏;Andriod横屏
$("body").attr("class","landscape");
orientation = 'landscape';
return false;
}
else if (window.orientation == 0 || window.orientation == 180) {
//ipad、iphone横屏;Andriod竖屏
$("body").attr("class","portrait");
orientation = 'portrait';
return false;
}
}
$(function(){
orient();
});
$(window).bind( 'orientationchange',function(e){
orient();
});
屏幕方向对应的 window.orientation 值:
ipad: 90 或 -90 横屏
ipad: 0 或 180 竖屏
Andriod:0 或 180 横屏
Andriod: 90 或 -90 竖屏
以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。