Javascript - modify CSS on HTML tag?

前端 未结 2 2067
北海茫月
北海茫月 2021-02-13 13:44

The HTML tag on this page I\'m working on is in a class that is giving it a top padding of 28px. I need this to go away temporarily when a button is cl

2条回答
  •  孤独总比滥情好
    2021-02-13 13:46

    There's no reason to use getElementsByTagName and whatnot...just use document.documentElement. Also, it's better to use a class and toggle that instead of directly setting the style attribute. What if you change the 28px to 20px in your CSS? Then you have to change it somewhere else. Since you are sure you want the top-padding to be 0, then add a class that sets that. When done, remove that class. Like this:

    
    
    document.documentElement.className += " no-top-padding";
    

    And to "add" the padding back (by effectively removing the class):

    var old_class = document.documentElement.className;
    document.documentElement.className = old_class.replace(/(?:^|\s)no-top-padding(?!\S)/g, "");
    

    Although it could be done a lot cleaner with the DOM API classList. The regex is just a safer way for making sure the className property is modified correctly to remove the "no-top-padding" class.

提交回复
热议问题