gpt4 book ai didi

javascript - 根据屏幕尺寸从特定 div 添加/删除类

转载 作者:行者123 更新时间:2023-12-03 05:18:39 25 4
gpt4 key购买 nike

当屏幕尺寸为>= 769px时,我需要添加类.full-page,并在屏幕尺寸为<=768时删除相同的类。我需要应用该类的 div 的 ID 为 #here 我已经尝试了很多事情,这就是我离开的地方...

<script>

var windowSize = window.innerWidth;

if (windowSize >= 769) {
console.log('Greater than 768');
document.getElementById('here').addClass = 'full-page';}

else (windowSize <= 768) {
console.log('Less than 768');
document.getElementById('here').removeClass = 'full-page';}

</script>

有人有提示吗?提前致谢!

最佳答案

您可以使用window#matchMedia检测宽度变化,并查看它是否符合特定标准。使用classList添加和删​​除类。

你可以看一个例子here 。通过拖动边框更改右下矩形的宽度。

<小时/>

代码:

var classList = document.getElementById('here').classList;

var minWidth769 = window.matchMedia("(min-width: 769px)");

function match() {
minWidth769.matches ? classList.add('full-page') : classList.remove('full-page');
}

minWidth769.addListener(match);

match();

关于javascript - 根据屏幕尺寸从特定 div 添加/删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494117/

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