当屏幕尺寸为>= 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/