简体   繁体   中英

CSS background via jQuery

I am trying to add a CSS attribute using jQuery but having an issue with the Background selector. Right now I have:

$('#nav_wrap').css({ 'position': 'fixed',
                     'margin-top':0,
                     'z-index':400,
                     'background-color': 'red',
                     'top':0,
                     'left':0 });

which gives the the color Red just fine, nothing wrong with the code. What I want to do is make it a gradient but when I change it to this:

 $('#nav_wrap').css({ 'position': 'fixed',
                      'margin-top':0,
                      'z-index':400,
                      'background': 'linear-gradient(top, #dc0000 0%,#650101 100%)',
                      'top':0, 'left':0 });

The background attribute doesnt get recognized. Any ideas why? Thanks.

As you demonstrated up to use classes instead of manually setting each CSS property for such purpose in the comments, here's how you would do it cross browser (IE8+):

CSS

.yourClass {
  position: fixed;
  margin-top: 0;
  z-index: 400;
  top: 0;
  left: 0;

  /* Safari 5.1, Chrome 10+ */
  background-image: -webkit-linear-gradient(top, #dc0000, #650101);

  /* Safari 4+, Chrome 2+ */
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#dc0000), to(#650101));

  /* FF 3.6+ */
  background-image: -moz-linear-gradient(top, #dc0000, #650101); 

  /* Opera 11.10 */ 
  background-image: -o-linear-gradient(top, #dc0000, #650101);

  /* Standard, IE 10 */
  background-image: linear-gradient(to bottom, #dc0000, #650101);

  /* IE8 */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdc0000', endColorstr='#ff650101', GradientType=0);
}

JS

$('#nav_wrap').addClass("yourClass");

Why don't you use classes and than add and remove class using jquery

$('#check').addClass('gradient'); //add class
$('#check').removeClass('gradient'); //remove class

FIDDLE

Try

$('#nav_wrap').css({ 'position': 'fixed',
                  'margin-top':0,
                  'z-index':400,
                  'background': 'linear-gradient(to bottom, #dc0000 0%,#650101 100%)',
                  'top':0, 'left':0 });

用这个 :

background: "-webkit-gradient(linear) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM