关于CSS3中的线性渐变

313 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

线性渐变用法

  • 使用角度指定渐变方向示例

    <style>
        .container div:nth-child(1) {
                /* 
                    linear-gradient(angle,color-stop,color-stop,...)
                    * angle - 通过角度方式来定义线性渐变的基准线的方向,单位为deg
                    * color-stop - 表示线性渐变的颜色以及位置
                 */
                background: linear-gradient(0deg,red,yellow);
            }
    </style>
    
  • 使用关键字指定渐变方向

    <style>
      .container div:nth-child(2) {
                /* 
                    linear-gradient(side-or-corner,color-stop,color-stop,...)
                    * side-or-corner - 通过关键字方式定义线性渐变的基准线的方向
                        * 一个关键字表示水平方向:left和right
                        * 一个关键字表示垂直方向:top和bottom
                        *注意
                            * 两个关键字与顺序无关
                            * 两个关键字都是可选的
                    * color-stop - 表示线性渐变的颜色以及位置
                 */
                background: -webkit-linear-gradient(left,red,yellow);
    </style>
    

background-clip属性

background-clip设置元素的背景(背景图片或颜色)是否延伸到边框下面。

如果没有设置背景颜色或图片,那么这个属性只有在边框(border) 设置为透明或

半透明时才能看到视觉效果(看border-styleborder- image),不然的话,

这个属性造成的样式变化会被边框覆盖住。

NNAZX8.png

用JS控制css3的动态效果

<script>
        var box = document.getElementById('box');
        /* 用于表示当前渐变颜色的位置 - 位置范围为 0 ~ 100*/ 
        var num = 0;
​
        setInterval(function(){
            if (num >= 100) {
                num = 0;
            } else { 
                box.style.background = 'linear-gradient(90deg,blue,red ' + num +'%,blue)';
        num++;
            }
        },10);
    </script>

NN3Qqs.gif