我如何在JavaScript中设置CSS渐变背景?

时间:2012-06-24 06:25:33

标签: javascript css3

CSS渐变描述为here,但我不知道如何在JavaScript中选择这些属性。如果可能的话,我宁愿不使用jQuery。

编辑:只是做以下似乎不起作用......

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)";

2 个答案:

答案 0 :(得分:1)

我不是JS专家,但我的猜测是你的设置会相互覆盖,所以你可能想要为.gradientBackground创建一个css类选择器,并查看下面的链接:

Change an element's class with JavaScript

答案 1 :(得分:0)

如果您不想使用jQuery,您想如何应用该样式?您应该创建一个包含每个浏览器渐变的类或ID。然后使用jQuery将该类设置为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');

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

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