我正在创建一个页面,该页面在creen大于500px时使用按钮显示内容,然后在屏幕小于500px时移动到“手风琴”样式布局。 我正在使用事件侦听器,并将媒体与if / else语句配合使用,以确定要运行的代码。
但是,当代码在小于500像素的窗口中运行,然后拖出以使其大于500像素时,按下按钮时,按钮不会响应'onclick'。
有人可以告诉我我在哪里错吗?
请参阅JSfiddle here
//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