嘿朋友,我正在尝试使用window.matchMedia("(max-width: 1700px)")
在页面小于等于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'
});
答案 0 :(得分:1)
几个问题。
x.addEventListener(adjustMenuDesign);
错误,因为addEventListener需要一个事件和一个回调。 但是您可能打算将其添加到resize事件中。
window.addEventListener("resize", adjustMenuDesign);
此外,您将需要在调整大小时再次运行matchMedia
查询,因此在此处将这段代码移入AdjustMenuDesign将很有意义。
以下是这些更改的有效提要。