Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

javascript - Setting multiple style.background values

I want to use gradients in my background and to be cross-platform I would like to set background with vendor prefixes:

background: -webkit-linear-gradient(red, blue);
background: -o-linear-gradient(red, blue);
background: -moz-linear-gradient(red, blue);
background: linear-gradient(red, blue);

How can I set multiple style.background's on a HTMLElement, using Javascript to support the vendor prefixes?

Update: I wish not to use jQuery or any other external library.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Another way is to set your props via the style attribute

 var styleText = '-webkit-linear-gradient(red, blue); ' +  
                 '-o-linear-gradient(red, blue); ' +
                'linear-gradient(red, blue);'

 el.setAttribute('style', styleText);

If you think you risk overriding any other styles already set inline you will want to get the current styles and then add the new ones on top:

var el = document.getElementById('myEl'),
    currentStyle = el.getAttribute('style'),
    styleText =  'background: -webkit-linear-gradient(top, red 0%,blue 100%); ' +  
                 'background: -o-linear-gradient(top, red 0%,blue 100%); ' +
                 'background: -ms-linear-gradient(top, red 0%,#blue 100%);' +
                 'background: linear-gradient(to bottom, red 0%, blue 100%);';


 el.setAttribute('style', currentStyle + styleText);

Here's a bin with an example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...