Modify CSS classes using Javascript

前端 未结 3 803
野性不改
野性不改 2020-12-30 00:23

I was wondering if there is an easy way to change the CSS classes in JavaScript. I have gone through all other similar questions here and I couldn\'t find an straight-forwar

相关标签:
3条回答
  • 2020-12-30 00:36

    If your rules start incrementing you could extract your css to a new class and switch classes:

    CSS:

    .container-1{
      /* A set of rules */
    }
    .container-2{
      /* A set of rules */
    }
    

    JavaScript:

    element.className = element.className.replace(/container-1/, 'container-2')
    
    0 讨论(0)
  • 2020-12-30 00:43
    var object = document.createElement('container');
    object.style.width= "500px";
    object.style.height= "600px";
    

    You can also add values to this if you hold the dimensions in variables

    var height = 600;
    var width = 500;
    

    You can increment when needed

    height += 5;
    

    Here is something you might find useful. It may offer you some insight on how you can solve a problem with many different approaches, seeing as though you are new to js.

    0 讨论(0)
  • 2020-12-30 00:53

    The reason only one or the other works is because in your second line of code, you destroy the whole style attribute, and recreate it. Note that setAttribute() overwrites the whole attribute.

    A better solution would be to use the element.style property, not the attribute;

    var bg = document.getElementById("myBg");
    bg.style.width = imgWidth + "px";
    bg.style.height = imgHeight + "px";
    

    You can grab all elements with class container and apply it to each of them like this:

    var elements = document.querySelectorAll('.container');
    for(var i=0; i<elements.length; i++){
        elements[i].style.width = imgWidth + "px";
        elements[i].style.height = imgHeight + "px";
    }
    

    Note querySelectorAll isn't supported by IE7 or lower, if you need those then there are shims for getElementsByClassName() here on SO.

    0 讨论(0)
提交回复
热议问题