我们知道,CSS支持将元素的border属性设为虚线,例如:
<h1>君喻学堂h1>
h1 {
border: dashed 1px;
}
但是,CSS的虚线样式是固定的,如果我们希望改变虚线的间隔,或者显示虚线滚动的动画效果,那么在CSS属性中是没办法做到的。
一个办法是使用SVG来模拟外框:
<div>
<h1>君喻学堂
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="2" y="2" width="200px" height="46px">rect>
svg>
h1>
div>
h1 {
position: relative;
width: 200px;
text-align: center;
margin-top: 20px;
margin-left: 20px;
/* border: dashed 1px; */
}
h1 svg {
position: absolute;
left: -2px;
top: -2px;
fill: transparent;
stroke: black;
stroke-width: 2;
stroke-dasharray: 5, 5;
stroke-dashoffset: 3;
animation: dashmove .5s linear infinite;
}
@keyframes dashmove {
0% {
stroke-dashoffset: 0;
}
100% {
stroke-dashoffset: 10;
}
}
因为svg元素支持stroke-dasharray和stroke-dashoffset属性,所以我们可以设置stroke-dasharray来改变虚线间隔,并通过改变stroke-dashoffset来实现滚动动画。最终实现的效果如下:
这么实现能够达到效果,但是这么实现也有明显的缺点:
改变了HTML结构,在h1中增加了svg标签。
还要根据h1的大小、border的宽度计算svg中rect标签的x、y、width、height
要解决这些问题,一个改进的办法是可以把SVG单独抽出来作为元素背景图片。
我们创建一个border.svg文件:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="2"
y="2"
width="200"
height="46"
fill="transparent"
stroke="black"
stroke-width="2"
stroke-dasharray="5,5"
stroke-dashoffset="3">
<animate attributeName="stroke-dashoffset"
from="0"
to="10"
begin="0s"
dur=".5s"
repeatCount="indefinite" />
rect>
svg>
在这里,我们把前面SVG的CSS属性改用SVG的属性实现,将css动画用SVG的SMIL动画实现。
然后我们的HTML、CSS就可以简化:
<h1>君喻学堂h1>
h1 {
position: relative;
width: 200px;
padding: 2px;
text-align: center;
margin-top: 20px;
margin-left: 20px;
background-image: url(https://s0.ssl.qhres.com/static/29d07f74b85903c0.svg);
background-repeat: no-repeat;
}
上面只要注意一个细节,因为我们的虚线框度为2px,所以我们要给h1元素设置一个padding:2px,将border需要的空间给腾出来。
这样我们就实现了同样的效果,而且HTML、CSS代码简单了。
但是这么做也有一个明显的问题,那就是,如果我们要修改虚线的样式或者动画,我们就要修改并更新SVG图片,这也让我们的代码维护起来比较麻烦。
那么有没有更好的办法解决这个问题呢?
如果你有任何想法,欢迎留言讨论。后续我们会专门开个CSS的专栏来深入讨论这类问题。
更多内容,尽在君喻学堂:《前端进阶十日谈》