简体   繁体   中英

How would I go about setting a CSS gradient background in JavaScript?

The CSS gradient is described here , but I have no idea how to select for these properties in JavaScript. I would rather not use jQuery for this if at all possible.

EDIT: Just doing the following doesn't seem to work...

document.getElementById("selected-tab").style.background = "#860432";
document.getElementById("selected-tab").style.background = "-moz-linear-gradient(#b8042f, #860432)";
document.getElementById("selected-tab").style.background = "-o-linear-gradient(#b8042f, #860432)";
document.getElementById("selected-tab").style.background = "-webkit-gradient(linear, 0% 0%, 0% 100%, from(#b8042f), to(#860432))";
document.getElementById("selected-tab").style.background = "-webkit-linear-gradient(#b8042f, #860432)";

I'm not a JS expert, but my guess is that your settings overwrite each other, so you might want to create a css class selector for this like .gradientBackground and check out the link below:

Change an element's class with JavaScript

If you don't want to use jQuery how do you want to apply the style? You should be creating a class or ID which contains the gradients for each browser. Then use jQuery to set that class to ID "selected-tab"

.someGradient{
    background: #1e5799; /* Old browsers */
    background: -moz-linear-gradient(top,  #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#2989d8), color-stop(51%,#207cca), color-stop(100%,#7db9e8)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* IE10+ */
    background: linear-gradient(top,  #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */
}

jQuery

$("#selected-tab").addClass('someGradient');

Before

 <div id='selected-tab' class='arial'>Hello world</div>

After

 <div id='selected-tab' class='arial someGradient'>Hello world</div>

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