【问题标题】:How to give an animation to border如何给边框动画
【发布时间】:2022-01-07 19:33:29
【问题描述】:

我有一个带有渐变边框的 div。所以我想给这个 div 一个动画,一旦它滚动到这个 div,我希望边框渐变自己旋转。我不知道该怎么做,所以我直接问它。

<div class="border-gradient">
          </div>

.border-gradient {
  height: 230px;
  width: 100%;
  border: 5px solid transparent;
  border-image: linear-gradient(190deg,  rgba(205, 0, 98,0) 10%, rgba(205, 0, 98,0.5));
  border-image-slice: 1;
}

【问题讨论】:

    标签: javascript html css animation css-animations


    【解决方案1】:

    我找不到用于动画边框的 css 解决方案,它可能可以使用图像来实现。

    无论如何,这是一个 javascript 解决方案

    var bored = document.getElementsByClassName("border-gradient")[0]; 
    var anim = {'running':0,'deg':0,'time':0};
    var animator;
    var boredy = bored.getBoundingClientRect().top;//grab the y of the element relative to the top of the web page
    checkscroll();//check if element onscreen initially
    
    window.onscroll = checkscroll;//check if element is onscreen when the user scrolls
    
    function checkscroll() {
    if(!anim.running && window.scrollY + window.innerHeight >= boredy) {
        anim.running = 1; anim.time = 0;//reset the animation, set running to 1 so the animation won't retrigger while already running
        startanim();
        }
    }
    
    function startanim() {
    animator = setInterval(function() {
    anim.deg += 1;
    anim.time += 50;
    
    bored.style = `border-image:linear-gradient(${anim.deg}deg,  rgba(205, 0, 98,0) 10%, rgba(205, 0, 98,0.5)); border-image-slice: 1;`;
    if(anim.time >= 10000){window.clearInterval(animator); anim.running = 0}
    },50);//start a loop that continousouly updates the border
    }
    

    CSS:

    .border-gradient {
      height: 230px;
      width: 100%;
      border: 5px solid transparent;
      border-image: linear-gradient(0deg,  rgba(205, 0, 98,0) 10%, rgba(205, 0, 98,0.5)); 
      border-image-slice: 1;
      margin-top:150vh;
    }
    

    当然可以改进。因此,请随意尝试并根据自己的喜好对其进行调整。

    【讨论】:

      【解决方案2】:

      您可以为边框设置动画:

      .border-gradient {
        border: solid 5px #FC5185;
        transition: border-width 0.6s linear;
      }
      .border-gradient:hover { border-width: 10px; }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        • 2013-08-23
        • 1970-01-01
        相关资源
        最近更新 更多