更改线性渐变的单色

时间:2016-02-19 10:59:11

标签: javascript css

如何使用Javascript在CSS线性渐变中更改第一种颜色?

div {
    background: -webkit-linear-gradient(top, #F6F6F6, #E9E9E9)
}

你可以看到我想改变颜色"#F6F6F6"仅

脚本必须是Javascript而不是jquery。

2 个答案:

答案 0 :(得分:0)

只需从div中删除该类,然后添加一个包含新属性的新类。

小提琴:https://jsfiddle.net/reko91/suuwe4wc/4/

我会添加另一个适用于所有div的类,在这种情况下' divs'和linearGradient类也是。

<div class='divs linearOne'>
</div>

只为按钮点击添加了JQuery

&#13;
&#13;
var divs = document.getElementsByClassName('divs');

var toggle = false; //used to toggle between

document.getElementById('clickme').addEventListener("click", function (event) {
  if(!toggle){ 
      divs[0].classList.remove('linearOne')
      divs[0].classList.add('linearTwo');
      toggle = true;
    } else {
      divs[0].classList.add('linearOne')
      divs[0].classList.remove('linearTwo');
      toggle=false;
      }

})
&#13;
.linearOne {
  width:100px;
  height:100px;
  background: -webkit-linear-gradient(top, #F6F6F6, #E9E9E9)
}

.linearTwo {
  width:100px;
  height:100px;
  background: -webkit-linear-gradient(top, #000000, #F6F6F6)
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divs linearOne'>

</div>

<button id='clickme'>
Toggle Gradient
</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您的<div>id,则使用JavaScript将背景更改为(1)其他渐变,(2)某种颜色,或(3)根本没有背景真的如此简单这个:

&#13;
&#13;
document.getElementById('anotherGradient').style.background = "-webkit-linear-gradient(top, #00E9E9, #F6F600)";
document.getElementById('greyBackground').style.background = "#E9E9E9";
document.getElementById('noBackground').style.background = "none";
&#13;
div {
    background: -webkit-linear-gradient(top, #F6F6F6, #E9E9E9)
}
&#13;
<div id="anotherGradient">
    This DIV should have a different gradient
</div>
<div id="greyBackground">
    This DIV should have a grey background but no gradient
</div>
<div id="noBackground">
    This DIV should not have any background at all
</div>
<div>
    This DIV should have the original gradient
</div>
<div>
    This DIV should have the original gradient
</div>
&#13;
&#13;
&#13; (另见this Fiddle