【发布时间】:2018-01-27 07:00:55
【问题描述】:
我正在使用 javascript 创建一个带有汉堡图标的按钮。它在所有浏览器和操作系统上都能正常工作,除了 Windows 10 家庭 PC 上的 Microsoft Edge。
这是我的代码(假设在代码的前面有任何未命名的变量或函数):
function isMobile() {
return window.outerWidth <= config.mobile.breakpointWidth
}
function toggleMobileClass() {
isMobile() ? addClass(MBody, "mdcre-mobile") : removeClass(MBody, "mdcre-mobile")
}
function getMobileOpenIcon() {
return '<i class="fa ' + config.mobile.navigation.button.icon.open + '"></i><span class="sr-only">Open Naviation</span>'
}
function getMobileCloseIcon() {
return '<i class="fa ' + config.mobile.navigation.button.icon.close + '"></i><span class="sr-only">Close Navigation</span>'
}
function addMobileNavButton() {
if (!document.getElementsByClassName("mdcre-nav-button")) {
var e = document.createElement("button");
e.classList += "mdcre-nav-button", e.innerHTML = getMobileOpenIcon(), e.addEventListener("click", function() {
toggleMobileNavVisibility(), toggleMobileNavButtonIcon()
}), MBody.appendChild(e)
}
}
function removeMobileNavButton() {
var e = document.getElementsByClassName("mdcre-nav-button")[0];
e && e.remove()
}
function toggleMobileNavButton() {
isMobile() ? addMobileNavButton() : removeMobileNavButton()
}
function toggleMobileNavVisibility() {
document.getElementById("lightbox-menu").style.display = document.getElementById("lightbox-menu").style.display === 'block' ? 'none' : 'block';
toggleClass(MHeader, 'show-nav');
toggleClass(MBody, 'no-scroll');
}
function toggleMobileNavButtonIcon() {
document.getElementsByClassName("mdcre-nav-button")[0].innerHTML = hasClass(MHeader, "show-nav") ? getMobileCloseIcon() : getMobileOpenIcon()
}
解释:当您低于某个大小(由变量breakpointWidth 在别处决定)时,会创建一个button 元素并为其分配mdcre-nav-button 类。
在 Microsoft Edge 上,它创建按钮元素,但不添加类。
我很确定问题出在 "addMobileNavButton" 函数上,但我不知道是什么让 Microsoft Edge 陷入困境。
其他信息:我只是在最近更新的 Windows 10 家用电脑上遇到了 Microsoft Edge 问题。同一台 PC 上的 Chrome 和 Firefox 中的代码可以正常工作。我在 iPhone 5c 上试用过 Microsoft Edge,效果也很好。
【问题讨论】:
-
为什么将
+=与classList一起使用?它不是一个字符串。使用e.classList.add() -
你的语法很奇怪。为什么要使用逗号而不是分号分隔多个语句?