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

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

本文关键字:设置 CSS 渐变 背景 JavaScript      更新时间:2023-09-26

这里描述了CSS梯度,但我不知道如何在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)";

我不是JS专家,但我的猜测是您的设置会相互覆盖,因此您可能希望为此创建一个css类选择器,例如.gradientBackground并查看以下链接:

使用 JavaScript 更改元素的类

如果你不想使用 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>