css border 虚线间距_【前端冷知识】CSS如何实现虚线框动画
我們知道,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的專欄來深入討論這類問題。
更多內容,盡在君喻學堂:《前端進階十日談》
總結
以上是生活随笔為你收集整理的css border 虚线间距_【前端冷知识】CSS如何实现虚线框动画的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何安装cad2012版(CAD2012
- 下一篇: 您的浏览器由所属组织管理_速度收藏!全省