我们如何切换 element
的类基于设备的方向。
例子:
<div class="landscape"></div>
@media (orientation: portrait) {
.landscape: {...}
}
我可以改变landscape
css 属性。但我想避免这种情况。相反,我想改变类本身,它看起来像
<div class="portrait"></div> // if orientation is portrait
<div class="landscape"></div> // if orientation is landscape
对此有任何建议!注意:将接受
vue
的答案以及更新:
screen.orientation
不适用于 safari
.解决方案应该适用于 safari
也。感谢您的回答。
最佳答案
使用 matchMedia
查看此代码.但也许我在这段代码的某个地方犯了一个错误。但本质和结构是正确的。
window.matchMedia('(orientation: portrait)').addListener(function(m) {
let div_class = document.querySelector('.landscape');
if (m.matches) {
div_class.className = 'portrait';
} else {
div_class.className = 'landscape';
}
});
关于javascript - 在javascript中切换方向更改类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63523099/