如何通过JavaScript更改线性渐变百分比?

时间:2017-02-20 17:40:49

标签: javascript html css linear-gradients

我想制作一个圆形背景,使用线性渐变逐渐填充。我有我的CSS和JavaScrpit文件,只是我无法弄清楚如何在JS中选择线性渐变属性。

 <div id="circle" class="circleBase "></div>
    #circle{
        width: 300px;
        height: 300px;
        background-color:blue;
        background: linear-gradient(90deg, #FFC0CB 0%,white 100%);
    }

    function changeBackground() {
        var elem = document.getElementById("circle"); 
        var width = 1;
        var id = setInterval(frame, 10);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
               width++; 
               elem.style = ????
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

只需将其定义为字符串:

elem.style.background = 'linear-gradient(180deg, #FFC0CB 0%,white 100%)';

function changeBackground() {
        var elem = document.getElementById("circle"); 
        var width = 1;
        var id = setInterval(frame, 10);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
               width++; 
               elem.style.background = 'linear-gradient(180deg, #FFC0CB 0%,white 100%)';
            }
        }
    }
    
 
#circle{
        width: 300px;
        height: 300px;
        background-color:blue;
        background: linear-gradient(90deg, #FFC0CB 0%,white 100%);
    }
<div id="circle"></div>
<button onclick="changeBackground()">Change!</button>