Toggle class on HTML element without jQuery

后端 未结 7 1472
时光说笑
时光说笑 2020-12-08 14:27

I have a section on my website which holds all the content, but I want a \"sidebar\" with hidden content to smoothly appear from the left at the push of an external button.<

7条回答
  •  不思量自难忘°
    2020-12-08 14:58

    // By Plain Javascript
    // this code will work on most of browsers. 
    function hasClass(ele, clsName) {
        var el = ele.className;
        el = el.split(' ');
        if(el.indexOf(clsName) > -1){
            var cIndex = el.indexOf(clsName);
            el.splice(cIndex, 1);
            ele.className = " ";
            el.forEach(function(item, index){
              ele.className += " " + item;
            })
        }
        else {
            el.push(clsName);
            ele.className = " ";
            el.forEach(function(item, index){
              ele.className += " " + item;
            })
        }
    }
    
    var btn =  document.getElementById('btn');
    var ele = document.getElementById('temp');
    
    btn.addEventListener('click', function(){
        hasClass(ele, 'active')
    })
    

提交回复
热议问题