orientationchange 监听横竖屏切换html
window.orientation 手机竖屏状态,有四个状态码。你们能够在真机尝试一下面试
<script> // alert(window.orientation) // orientationchange监听手机的横竖屏发生切换 window.addEventListener("orientationchange",()=>{ alert(window.orientation); }) </script>
像王者荣耀的一些活动页面不但愿用户在横屏状态下浏览,这里咱们也能够实现函数
思路:监听用户横竖屏状态,当状态为90和-90时,咱们显示一个box,对用户进行提示。spa
下面是例子:code
<script> showBox(); window.addEventListener("orientationchange",showBox()) function showBox(){ let box = document.querySelector("#box"); switch(window.orientation){ case 90: case -90: box.style.display = "block"; break; default: box.style.display = "none"; } } </script>
devicemotion 监听手机加速度发生变化orm
htm
blog
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> #box{ width: 300px; height: 300px; background: red; color: #fff; font:14px/30px "宋体"; } </style> <body> <div id="box"></div> <script> window.addEventListener("deviceorientation",(e)=>{ let {x,y,z} = e.acceleration; box.innerHTML = ` 手机x方向加速度:${x}</br> 手机y方向加速度:${y}</br> 手机z方向加速度:${z}</br> ` }) </script> </body> </html>
在这里若是你是IOS手机,咱们将会遇到一些坑!!!接口
有了上面的基础,咱们能够来制做一个简易的小游戏——移动的方块游戏
这里要注意一点:IOS 和 安卓的取值 是恰好相反
因此咱们须要进行一个判断,对IOS和安卓进行兼容处理。
function getIos(){ var u = window.navigator.userAgent; return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); }
接下来就是实现咱们的小游戏
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box { position: absolute; left: 50%; top: 50%; margin: -25px 0 0 -25px; width: 50px; height: 50px; background: red; } </style> </head> <body> <div id="box"></div> <script> let box = document.querySelector("#box"); let translateX = 0; function getIos(){ let u = window.navigator.userAgent; return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); } // 注意 IOS 和 安卓的取值 恰好相反 // x轴 IOS 下是 10 ,那安卓下就是 -10 window.addEventListener("devicemotion",(e)=>{ let {x} = e.accelerationIncludingGravity; let {x:x2} = e.acceleration; x -= x2; if(!getIos()){ x = -x; } translateX += x; box.style.transform = `translateX(${translateX}px)`; }); </script> </body> </html>
明天的重点即是面试常出现的函数防抖和函数节流!