clip-path 实现边框线条动画,边框loading轻松实现!

117 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情

前言

掘友们,大家好啊。最近小编的项目中,测试已经很难找出bug了。所以,产品为了不让我闲着,提了一个需要优化的点,就很nice。因为项目中可能出现的卡片形式比较多吧,然后卡片的loading也是比较常见的,从一开始的全局loading要换成局部loading,又嫌弃人家ui库的loading,就很离谱。提到了能不能在卡片的周围加loading呢?能,当然能。

这里小编也是调研了工作,阅读了许多的帖子,后来从昔日的老同学那里找到了文章,实现了边框线条动画加载效果。

如图所示:

tdlfr-mak0s.gif

代码实现

html

<div>Hello</div>

css

body,
html {
    width: 100%;
    height: 100%;
    display: flex;
}

div {
    position: relative;
    margin: auto;
    width: 120px;
    line-height: 64px;
    text-align: center;
    color: #fff;
    font-size: 20px;
    border: 2px solid gold;
    border-radius: 10px;
    background: gold;
    transition: all .3s;
    cursor: pointer;
    
    &:active {
        filter: contrast(0.9);
    }
    
    &::before,
    &::after {
        content: "";
        position: absolute;
        top: -10px;
        left: -10px;
        right: -10px;
        bottom: -10px;
        border: 2px solid gold;
        transition: all .5s;
        animation: clippath 3s infinite linear;
        border-radius: 10px;
    }
    
    &::after {
        animation: clippath 3s infinite -1.5s linear;
    }
}

@keyframes clippath {
    0%,
    100% {
        clip-path: inset(0 0 98% 0);
    }
    
    25% {
        clip-path: inset(0 98% 0 0);
    }
    50% {
        clip-path: inset(98% 0 0 0);
    }
    75% {
        clip-path: inset(0 0 0 98%);
    }
}

这里是通过,clip-path 实现边框线条动画。clip-path CSS 属性可以创建一个只有元素的部分区域可以显示的剪切区域。区域内的部分显示,区域外的隐藏。剪切区域是被引用内嵌的URL定义的路径或者外部 SVG 的路径。因为使用了 clip-path 裁剪后的元素,只有元素的剪切区域才能被显示,所以我们可以通过动画 animation 将几个关键帧绘制出来即可。

文档地址:csscoco.com/inspiration…

结尾

希望文章对大家有所帮助,小编会不间断的更新每天的工作内容了,遇到的小功能了什么的,喜欢的可以点个赞,或关注小编,后续更文。