Javascript - modify CSS on HTML tag?

前端 未结 2 2068
北海茫月
北海茫月 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:

    <style type="text/css">
        .no-top-padding {
            padding: 0 !important;
        }
    </style>
    
    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.

    0 讨论(0)
  • 2021-02-13 13:55

    Use this to remove the top padding:

    document.documentElement.style.paddingTop = "0";
    

    and this to set it back:

    document.documentElement.style.paddingTop = "28px";
    
    0 讨论(0)
提交回复
热议问题