Change Div style onclick

后端 未结 6 1605
逝去的感伤
逝去的感伤 2021-01-15 14:07

I have 2 tabs at the top of a page. When one tab is clicked, I would like that tab to have an \"active\" class and the other tab to have an \"inactive\" class so that the us

6条回答
  •  广开言路
    2021-01-15 14:23

    Give your tabs a class of "tab"... HTML:

    ...
    ...

    JS:

    function getByClass(_class, elem) {
        var i, result = [], elems = document.getElementsByTagName("div"); //get the elements
       for (i = 0; i < elems.length; i++) {
            if (elems[i].className.indexOf(_class) !== -1) { //if the elements have the class passed in, add it to the result array
                result.push(elems[i]);
            }
        }
        return result;
    }
    var i, tabs = getByClass("tab", "div"); //get all divs with class tab
    for (i = 0; i < tabs.length; i++) { //for each tab...
        tabs[i].onclick = function() { //wire up it's click event...
            //to clear the other tabs...
            var j;
            for(j=0; j < tabs.length; j++) {
               tabs[j].className = tabs[j].className.replace(" active", "");
            }
           this.className += " active"; //where active is a class predefined in the CSS 
        };
    }
    

    http://jsfiddle.net/thomas4g/pqMq2/12/

提交回复
热议问题