Vanilla JS Nav切换

时间:2016-09-04 12:15:31

标签: javascript

所以通常我习惯了jQuery,而我正试图冒险进入vanilla Javascript。我正在尝试通过单击链接来打开和关闭子窗口,但它只触发最后一项。我假设它与循环有关。谁能给我一些建议?

    var hasClass = function (elem, className) {
        return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
    }

    var addClass = function (elem, className) {
        if (!hasClass(elem, className)) {
            elem.className += ' ' + className;
        }
    }

    var removeClass = function (elem, className) {
        var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' ';
        if (hasClass(elem, className)) {
            while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
                newClass = newClass.replace(' ' + className + ' ', ' ');
            }
            elem.className = newClass.replace(/^\s+|\s+$/g, '');
        }
    }

    var navSections = document.querySelectorAll('.nav-toggle');
    for (var i = 0; i < navSections.length; i++) {

        var navSection = navSections[i];

        navSection.addEventListener('click', function(e) {

                console.log(navSection)

                if ( hasClass(navSection, 'nav-section--is-open') ) {
                    removeClass(navSection, 'nav-section--is-open')
                } else {
                    addClass(navSection, 'nav-section--is-open')
                }

        }, false);
    }

0 个答案:

没有答案