原生js封装函数,addClass removeClass,常用tag切换

  // 根据class 获取元素
var getElement = function(selector) {
        return document.querySelector(selector);
    }
    // 根据class 获取所有class 的元素
var getAllElement = function(selector) {
        return document.querySelectorAll(selector);
    }
    // 获取元素class
var getClass = function(element) {
        return element.getAttribute("class");
    }
    // 给元素设置class
var setClass = function(element, cls) {

        return element.setAttribute("class", cls);
    }
    // 给元素添加样式
var addClass = function(element, cls) {
        var baseCls = getClass(element);
        if (baseCls.indexOf(cls) === -1) {
            setClass(element, baseCls + " " + cls);
        }
    }
    // 元素删除指定样式

var delClass = function(element, cls) {
    var baseCls = getClass(element);
    if (baseCls.indexOf(cls) != -1) {
        setClass(element, baseCls.split(cls).join(' ').replace(/\s+/g, ' '));
    }
}




function nav_onclick(el) {
     var list_item = getAllElement(el);
     var _len = list_item.length;
     if (list_item) {
        for (var i = 0; i < _len; i++) {
            list_item[i].onclick = function () {
                for (var i = 0; i < _len; i++) {
                    delClass(list_item[i],"active");
                }
                addClass(this,"active");
            }
        }
     }
}

nav_onclick(".el"); 


function navTag(nav_ls_id, nav_con_id,nav_ls_item,nav_con_item) {
    if (document.getElementById(nav_ls_id) && document.getElementById(nav_con_id)) { 
        var nav_ls_item = document.getElementById(nav_ls_id).getElementsByTagName(nav_ls_item);
        var nav_con_item = document.getElementById(nav_con_id).getElementsByTagName(nav_con_item);
        var len = nav_ls_item.length;
        addClass(nav_ls_item[0],"active")
        addClass(nav_con_item[0],"active")
        for (var i = 0; i < len; i++) {
            nav_ls_item[i].setAttribute("data-index", i);
            nav_con_item[i].setAttribute("data-index", i);
        }
        for (var i = 0; i < len; i++) {
            nav_ls_item[i].onclick = function() {
                for (var i = 0; i < len; i++) {
                    delClass(nav_ls_item[i],"active");
                    delClass(nav_con_item[i],"active")
                }
                addClass(this,"active")
                _index = this.getAttribute("data-index");
                addClass(nav_con_item[_index],"active")            }
        }
   }
}
navTag("cat_hot", "hot_con","a","dl")

你可能感兴趣的:(javascript)