setting browser-specific CSS properties with jQuer

2019-08-01 02:39发布

问题:

I'm trying to modify gradient values in the background-image property and I can't :(

  data = 'ff55dd';
  $(".el").css({
    'background-image' : '-webkit-gradient(linear, left top, left bottom, from(#' + data + '), to(#aa1133))',
    'background-image' : '-webkit-linear-gradient(#' + data + ', #aa1133)',
    'background-image' : '-moz-linear-gradient(#' + data + ', #aa1133)',
    'background-image' : '-o-linear-gradient(top, #ff3345, #aa1133)',
    'background-image' : '-khtml-gradient(linear, left top, left bottom, from(#' + data + '), to(#aa1133))',
    'filter'           : 'progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#' + data' + '\', endColorstr=\'#aa1133\', GradientType=0)',
    'background-image' : 'linear-gradient(#ff5534, #aa1133)'
  });

Nothing happens.....

回答1:

Looks like its overwriting the rules if you put them in all at once.

I added them one by one and it seems to work.

    $(".e1")
      .css('background-image','-webkit-gradient(linear, left top, left bottom, from(#' + data + '), to(#aa1133))')
      .css('background-image','-webkit-linear-gradient(#' + data + ', #aa1133)')
      .css('background-image','-moz-linear-gradient(#' + data + ', #aa1133)')
      ...


回答2:

This is not going to work. Why? Because in that call to ".css()" you're not actually writing CSS code, you're writing JavaScript code. In an object constant, when you supply many different values for the same property name, you'll end up with just one property by the time the ".css()" code actually gets the object as a parameter. Therefore, only the very last "background-image" value you set will be left. All the others will be overwritten.

In other words, your code is equivalent to this:

$(".el").css({
    'filter'           : 'progid:DXImageTransform.Microsoft.gradient(startColorstr=\'#' + data + '\', endColorstr=\'#aa1133\', GradientType=0)',
    'background-image' : 'linear-gradient(#ff5534, #aa1133)'
});

I doubt there's any way to do this via jQuery other than to directly set the "style" attribute to the complete block of CSS, or to write the CSS into a constructed <style> element that you add to the DOM.