我正在制作一个页面,当屏幕宽度大于 500 像素时使用按钮显示内容,然后当屏幕小于 500 像素时,它会移动到“手风琴”样式布局。我正在使用事件侦听器并匹配媒体以及 if/else 语句来确定要运行的代码。
但是,当代码以小于 500 像素的窗口运行,然后将其拖出以使其大于 500 像素时,按钮在按下时不会响应“onclick”并且没有任何反应。
有人可以告诉我这里哪里出错了吗?
//Start listing variables for use in array.
var art1 = document.getElementById("article1");
var button1 = document.getElementById("list1");
var art2 = document.getElementById("article2");
var button2 = document.getElementById("list2");
var art3 = document.getElementById("article3");
var button3 = document.getElementById("list3");
var articleArray = [art1, art2, art3];
var buttonArray = [button1, button2, button3];
function mediaQuery(x) {
//If window is under 500px in width.
if (x.matches) {
//Begin accordion code
var initAccordion = function(accordionElement) {
function handlePanelClick(event) {
showPanel(event.currentTarget);
}
function showPanel(panel) {
var expandedPanel = accordionElement.querySelector(".active");
if (expandedPanel) {
expandedPanel.classList.remove("active");
}
panel.classList.add("active");
}
var allPanelElements = accordionElement.querySelectorAll(".panel");
for (var y = 0; len = allPanelElements.length; y++ ) {
allPanelElements[y].addEventListener("click", handlePanelClick);
}
showPanel(allPanelElements[0]);
}
initAccordion(document.getElementById("contentWrapper"));
}
else //If window if is over 500px in width.
{
//Begin button code.
var createfunc = function (i) {
return function() { document.getElementById("fillMe").innerHTML = articleArray[i].innerHTML;};
}
for (let i=0; i < articleArray.length; i++) {
let button = buttonArray[i];
button.addEventListener("click", createfunc(i));
}
}
}
//Declare media query and add listener.
var x = window.matchMedia("(max-width: 500px)")
mediaQuery(x) // Call listener function at run time
x.addListener(mediaQuery) // Attach listener function on state changes