Reputation: 51
I need to dynamically generate CSS patterns, for which I need to apply several linear-gradient
or radial-gradient
to the CSS background
property on the client side. And I need to dynamically change the parameters of these gradients at the same time.
If I use this, only one gradient is applied to the background:
var color1;
var color2;
var color3;
var color4;
var direction1;
var direction2;
var direction3;
var direction4;
var size;
$("body").css({
background: 'linear-gradient('+direction1+', '+color1+' 25%, transparent 25%) '+size+'/2 0,
linear-gradient('+direction2+', '+color2+' 25%, transparent 25%) '+size+'/2 0,
linear-gradient('+direction3+', '+color3+' 25%, transparent 25%),
linear-gradient('+direction4+', '+color4+' 25%, transparent 25%)'
});
Same thing happens here, since each property overwrites the other:
$("body").css('background','linear-gradient('+direction1+', '+color1+' 25%, transparent 25%) '+size+'/2 0)');
$("body").css('background','linear-gradient('+direction2+', '+color2+' 25%, transparent 25%) '+size+'/2 0)');
$("body").css('background','linear-gradient('+direction3+', '+color3+' 25%, transparent 25%)');
$("body").css('background','linear-gradient('+direction4+', '+color4+' 25%, transparent 25%)');
I've tried using LessCSS
, but it's too CPU intense, since it needs to render a new stylesheet each time the css property changes, which is each time the mouse moves (that's a requirement).
Note that I need to apply ALL of the gradients at once, not let the browser decide which one to use.
Question 1: Any idea how I could do this more efficiently?
Question 2:
I've also noticed that when I declare multiple properties in one declaration (ie. also width
and height
next to the linear-gradient
in a background
property or just even just width
and height
using the background-size
property) only the first one gets applied. How to get around this?
Upvotes: 1
Views: 1017
Reputation: 2195
Try somthing like this:
$("body").css({
'backgroundImage': 'linear-gradient('+direction1+', '+color1+', transparent),
linear-gradient('+direction2+', '+color2+', transparent),
linear-gradient('+direction3+', '+color3+', transparent),
linear-gradient('+direction4+', '+color4+', transparent)'
})
Upvotes: 1