随时互联网高速发展和智能的手机的广泛应用,网站由之前单一电脑访问转变为自动匹配多终端访问。在做网站建设时针对移动端特别是手机端用户访问时随时考虑到在横屏和竖屏下的显示状态,今天就和大家一起探讨下网站在移动端访问中如何自动匹配横竖屏,如果你的网站不支持横屏那么当用户横屏时又如何给出相关提示?
首先我们来介绍如何分别用html、JS和CSS如何检测横竖屏:
1、HTML检测代码:
<!-- 引用竖屏的CSS文件 portrait.css --> <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow" > <!-- 引用横屏的CSS文件 landscape.css --> <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow" >
2、CSS方法检测:
css中通过媒体查询方法来判断是横屏还是竖屏
/* 竖屏 */
@media screen and (orientation:portrait) {
/* 这里写竖屏样式 */
}
/* 横屏 */
@media screen and (orientation:landscape) {
/* 这里写横屏样式 */
}
3、JS方法检测
【1】orientationChange事件
苹果公司为移动 Safari中添加了 orientationchange 事件,orientationchange 事件在设备的纵横方向改变时触发
window.addEventListener("orientationchange",function(){
alert(window.orientation);
});
【2】orientation属性
window.orientation 获取手机的横竖的状态,window.orientation 属性中有 4个值:0和180的时候为竖屏(180为倒过来的竖屏),90和-90时为横屏(-90为倒过来的横屏)
0 表示肖像模式,90 表示向左旋转的横向模式(“主屏幕”按钮在右侧),-90 表示向右旋转的横向模 式(“主屏幕”按钮在左侧),180 表示 iPhone头朝下;但这种模式至今 尚未得到支持。如图展示了 window.orientation 的每个值的含义。
最后就是手机在横竖屏状态下给出提示:
检测用户当前手机横竖屏状态,如果处于横屏状态,提示用户 “为了更好的观看体验,请在竖屏下浏览”,否则不提示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#box {
position: fixed;
box-sizing: border-box;
padding: 50px;
display: none;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, .5);
}
#box span {
margin: auto;
font: 20px/40px "宋体";
color: #fff;
text-align: center;
}
</style>
</head>
<body>
<div id="box"><span>为了更好的观看体验,请在竖屏下浏览</span></div>
<script>
window.addEventListener("orientationchange", toOrientation);
function toOrientation() {
let box = document.querySelector("#box");
if (window.orientation == 90 || window.orientation == -90) {
// 横屏-显示提示
box.style.display = "flex";
} else {
// 横屏-隐藏提示
box.style.display = "none";
}
}
</script>
</body>
</html>
好了,以上内容就是今天和大家探讨的关于如果在手机的横竖屏下分别通过HTML、JS和CSS代码来判断检测并给也相关提示的全部内容,希望对你的网站建设有所帮助,喜欢的话记得收藏哦!