jQuery: Temporarily change a style then reset to original class

后端 未结 4 1354
一向
一向 2020-12-13 05:33

Say I have a class named testThing:

.testThing
{
   background-color:#000000;
   float:left;
   height:50px;
   width:50px;
}

And I want to

相关标签:
4条回答
  • 2020-12-13 06:10

    Jquery adds CSS in the style attribute which has higher priority over what is in your CSS file. You're not changing your CSS document with that function and thus adding and removing and adding the class have no effect since it hasn't been modified at all!

    You should use the same function but set the background color to black this time.

    function reset(this)
    {
      $(this).css('background-color', '#000000');
    }
    

    Or simply remove the style attribute

    function reset(this)
    {
      $(this).removeAttr('style');
    }
    
    0 讨论(0)
  • 2020-12-13 06:11

    I know this is old, but you can just set the value to an empty string to remove your custom style like so:

    // set
    $(this).css('background-color', '#000000');
    
    // reset
    $(this).css('background-color', '');
    
    0 讨论(0)
  • 2020-12-13 06:16

    It is better to just add another class that overrides the style you want to change and then remove it. It beats hard coding style info inside the js. The only issue is youll have to ensure the added class is of a higher order so that the element takes the style from it rather than the existing class but this is not hard to ensure.

    0 讨论(0)
  • 2020-12-13 06:19

    What about toggleClass("testThing")? I use it when there's more than one property to change.

    http://api.jquery.com/toggleClass/

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