问题描述
<script>
window.addEventListener(
'resize',HideWithResize
)
</script>
我知道我的 JS 看起来很糟糕,但我只是在尝试:
var HideWithResize = function() {
if ($(window).width() < 1024) {
$('.nav__paragraph--news').hide();
$('.nav__paragraph--abwesend').hide();
document.querySelector(".dropdown__news").classList.replace("dropdown__news--active","dropdown__news--inactive");
document.querySelector(".dropdown__abwesend").classList.replace("dropdown__abwesend--active","dropdown__abwesend--inactive");
} else if ($(window).width() > 1024 ) {
$('.nav__paragraph--news').show();
$('.nav__paragraph--abwesend').show();
document.querySelector(".dropdown__news").classList.replace("dropdown__news--inactive","dropdown__news--active");
document.querySelector(".dropdown__abwesend").classList.replace("dropdown__abwesend--inactive","dropdown__abwesend--active");
}
};
假设有人打开一个大小为 1500 的窗口并将其缩小到 1024 以下,它应该隐藏 2 个段落。当他用下拉箭头打开较小窗口上的段落并再次缩小窗口(甚至增加到 1024)时,它会再次隐藏段落...... 但是在低于 1024 的限制后我只需要做一次...... 与有人在 1024 以下打开它并将其增加到 1024 以上,它总是在调整大小后再次显示内容
另一件事是,当有人打开低于 1024 的网站时,段落应该被隐藏,直到他打开它们 --> 然后它们应该保持打开状态
有什么想法可以解决吗?
提前致谢!
找到解决方案:
function HideWithResize() {
var prevWidth = 0;
$(document).ready(function() {
prevWidth = $(window).width();
});
$(window).resize(function() {
var currentWidth = $(window).width();
if (prevWidth > 1024 && currentWidth < 1024) {
$('.nav__paragraph--news').hide();
$('.nav__paragraph--abwesend').hide();
document.querySelector(".dropdown__news").classList.replace("dropdown__news--active","dropdown__news--inactive");
document.querySelector(".dropdown__abwesend").classList.replace("dropdown__abwesend--active","dropdown__abwesend--inactive");
} else if (prevWidth < 1024 && currentWidth > 1024) {
$('.nav__paragraph--news').show();
$('.nav__paragraph--abwesend').show();
document.querySelector(".dropdown__news").classList.replace("dropdown__news--inactive","dropdown__news--active");
document.querySelector(".dropdown__abwesend").classList.replace("dropdown__abwesend--inactive","dropdown__abwesend--active");
}
prevWidth = currentWidth;
});
}
解决方法
您想要的是检查用户是否将窗口放大或缩小。仅在窗口变小时时触发。
但是,window.addEventListener('resize',HideWithResize)
会触发 any 调整大小。因此,您需要一个 If 语句,将旧窗口大小与新窗口大小进行比较,然后执行相应操作。