1

嘿朋友们,当页面为 1700 像素或更小时,我正在尝试window.matchMedia("(max-width: 1700px)")在 html 中添加一些元素。现在我只是想通过在屏幕上显示一个功能警报“哟”来测试它。这和我试图改变的其他事情一样不起作用?有任何想法吗?

https://jsfiddle.net/yat5ncmk/6/

const ham = document.querySelector('.nav-box');
const menu = document.querySelector('.menu');
const menuClose = document.querySelector('#menu-close');
const leftArrow = document.querySelector('#left');
const rightArrow = document.querySelector('#right');
const img = document.querySelector('.image-slider');
var x = window.matchMedia("(max-width: 1700px)");
let num = 1;

x.addEventListener(adjustMenuDesign);
adjustMenuDesign(x);

ham.addEventListener('click', function() {
	ham.classList.add('ham-open');
	menu.style.marginLeft = '50px';
})

menuClose.addEventListener('click', function() {
	ham.classList.remove('ham-open');
	menu.style.marginLeft = '-700px';
})

leftArrow.addEventListener('click', function() {
	num--;
	if(num > 0) {
		img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
		console.log(num);
		console.log(img.style.backgroundImage);
	} else {
		num = 4;
		img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
	}
})

rightArrow.addEventListener('click', function() {
	num++;
	if(num <= 4) {
		img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
		console.log(num);
		console.log(img.style.backgroundImage);
	} else {
		num = 1;
		img.style.backgroundImage = 'url(img/fam-' + num + '.jpeg)';
	}	
})

function adjustMenuDesign(width) {
    if (width.matches) { // If media query matches
	    alert('yo');
	} 
}

window.sr = ScrollReveal();

sr.reveal('.logo-wrap', {
	duration: 2000
});

sr.reveal('.w1', {
	duration: 2000,
	origin: 'bottom'
});

sr.reveal('.w2', {
	duration: 3000,
	origin: 'bottom'
});

sr.reveal('.w3', {
	duration: 4000,
	origin: 'bottom'
});

sr.reveal('.hours-line-left', {
	duration: 1000,
	origin: 'left',
	distance: '200px'
});

sr.reveal('.hours-line-right', {
	duration: 1000,
	origin: 'right',
	distance: '200px'
});

sr.reveal('.contact-line', {
	duration: 1000,
	origin: 'bottom',
	distance: '250px'
});

sr.reveal('.burrito', {
	duration: 1000,
	origin: 'right',
	distance: '250px'
});

sr.reveal('.taco', {
	duration: 1000,
	origin: 'right',
	distance: '250px'
});

sr.reveal('.guac', {
	duration: 1000,
	origin: 'right',
	distance: '250px'
});

sr.reveal('.nachos', {
	duration: 1000,
	origin: 'bottom',
	distance: '250px'
});

sr.reveal('.hot', {
	duration: 1000,
	origin: 'left',
	distance: '250px'
});

sr.reveal('.back-to-top', {
	duration: 1000,
	origin: 'bottom',
});

sr.reveal('.btp-arrow', {
	duration: 1500,
	origin: 'top',
	distance: '250px'
});

4

1 回答 1

1

几个问题..

x.addEventListener(adjustMenuDesign);

错误,因为 addEventListener 需要一个事件和一个回调。但是您可能打算将其添加到调整大小事件中。

window.addEventListener("resize", adjustMenuDesign);

此外,您还需要matchMedia在调整大小时再次运行查询,因此将这段代码移入 adjustMenuDesign 在这里是有意义的。

下面是这些变化的工作小提琴。

https://jsfiddle.net/veckopab/

于 2019-05-22T22:45:51.950 回答