已弃用:窗口:orientationchange 事件

Bho*_*yar 8 javascript

orientationchange事件已被弃用。

window.addEventListener("orientationchange", function(event) {
  console.log(event.target.screen.orientation.angle);
});
Run Code Online (Sandbox Code Playgroud)

窗口:orientationchange 事件

已弃用 不再推荐此功能。尽管某些浏览器可能仍然支持它,但它可能已从相关网络标准中删除,可能正在被删除,或者可能仅出于兼容性目的而保留。避免使用它,并尽可能更新现有代码;请参阅本页底部的兼容性表来指导您的决定。请注意,此功能可能随时停止工作。

我现在可以用什么?有没有其他方法可以做到这一点?

Bho*_*yar 6

我们可以使用实验性功能ScreenOrientation

screen.orientation.addEventListener('change', function(e) { ... })
screen.orientation.onchange = function(e) { ... }
Run Code Online (Sandbox Code Playgroud)

您可以从屏幕方向表中检查方向类型的可用值:

  • 纵向-主要
  • 肖像次要
  • 景观为主
  • 景观-次要

这是一个例子:

screen.orientation.addEventListener('change', function(e) {
  if (e.currentTarget.type === 'landscape-primary') {
    // landscape mode => angle 0
  } else if (e.currentTarget.type === 'portrait-primary') {
    // portrait mode => angle 0
  }
})
Run Code Online (Sandbox Code Playgroud)

检查浏览器兼容性表

  • Safari 的另一件事是在兼容方面落后...... (3认同)