为什么方向更改事件不会在桌面上触发?

时间:2019-12-23 06:16:04

标签: javascript html

我知道在台式机上没有这样的“方向更改”概念,但是chrome开发工具内部提供了更改方向的选项。我看到在更改方向时触发了“调整大小”事件,这是合理的..由于AxB变为BxA,但是为什么连方向都不触发?

当在任何设备上更改方向时,我可以使用哪种方法来确保可以触发事件?

index.html:

<html lang="en">
    <head>
    </head>
    <body>
        <script src="./main.js"></script>
    </body>
</html>

main.js:

window.addEventListener("orientationchange", function(){
    this.console.log("orientation changed")
});
window.addEventListener("resize", function(){
    this.console.log("resized")
});

我什至尝试了jquery事件处理程序,但不起作用。

在适用于Mac的Chrome 79上。 谢谢。

1 个答案:

答案 0 :(得分:1)

如果您对方向变化感兴趣,

orientationchange是正确的事件。

您所描述的内容应该可以在您的开发工具中使用,因为这些工具将扩展可用的Web-API,从而使桌面浏览器的行为像移动浏览器一样,可以真正改变方向。
在macO上的Chrome 79上,单击响应模式的“旋转”图标可使事件触发。

screenshot of the page in responsive mode with the console output showing an orientationchange event has fired


现在,如果您希望检查什至是桌面浏览器在垂直模式或水平模式下通过,您仍然可以选择添加MediaQuery

const query = matchMedia("screen and (orientation:portrait)");

query.onchange = e => {
  console.log( 'orientation change', query.matches ? 'portrait' : 'landscape' );
  // though beware square will be marked as landscape here,
  // if you want to handle this special case
  // create an other mediaquery (orientation:landscape) 
}
You may have to run this snippet in "full page" mode

相关问题