Toggle class on HTML element without jQuery

后端 未结 7 1475
时光说笑
时光说笑 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条回答
  •  Happy的楠姐
    2020-12-08 15:01

    you can get any element by id with javascript (no jquery) and the class is an attribute : element.className so have this as a function:

    UPDATE: since this is becoming a somewhat popular I updated the function to make it better.

    function toggleClass(element, toggleClass){
       var currentClass = element.className;
       var newClass;
       if(currentClass.split(" ").indexOf(toggleClass) > -1){ //has class
          newClass = currentClass.replace(new RegExp('\\b'+toggleClass+'\\b','g'),"")
       }else{
          newClass = currentClass + " " + toggleClass;
       }
       element.className = newClass.trim();
    }
    

提交回复
热议问题