gpt4 book ai didi

javascript - 在javascript中切换方向更改类

转载 作者:行者123 更新时间:2023-12-01 15:38:12 26 4
gpt4 key购买 nike

我们如何切换 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com