Remove the added style with .css () function with jQuery

5

I'm changing CSS with jQuery and need to remove the style I've added:

if(cor != 'ffffff') $("body").css("background-color", cor); else // remover style ?

The above line runs whenever a color is selected using a color picker when the mouse moves over a color wheel.

I can not do this with css, with "background-color", "none" because it will remove the default style from css files. I just want to remove the inline style of background color added by jQuery.

    
asked by anonymous 14.12.2017 / 11:46

3 answers

1

There are several ways to remove a CSS property using jQuery:

1. Setting the CSS property to its default (initial) value

.css("background-color", "transparent")
  

See the initial value for the CSS property in MDN . Here, the value   pattern is transparent. You can also use inherit for several   CSS properties to inherit the attribute from its parent. In CSS3 / CSS4,   you can also use initial , revert or unset , but these   keywords may have limited browser support.

2. Removing CSS property

An empty string removes the CSS property:

.css("background-color","")

3. Removing all style from element

.removeAttr("style")
    
14.12.2017 / 11:53
1

You can change the property for an empty string to do this:

$("body").css("background-color", "");

Or remove the full attribute, the problem would be that all inline styles of the element would be removed:

 $("body").removeAttr("style");
    
14.12.2017 / 11:51
0

Leaving transparent can solve the problem.

$(document).ready(function(){
    $('ul > li').on('click', function(){
      var cor   = $(this).data('cor');
      var body  = $('body');
      
      body.css('background-color', cor);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body></body><ul><lidata-cor="#FF0000">Cor 1</li>
<li data-cor="#FFFF00">Cor 2</li>
<li data-cor="#0000FF">Cor 3</li>
<li data-cor="#00FF00">Cor 4</li>
<li data-cor="transparent">Nenhuma</li>
</ul>
    
14.12.2017 / 11:50