点击右上方红色按钮关注“web秀”,让你真正秀起来
前言
纯CSS制作一个评星组件,说出去都没人信,你信吗?
如果让你制作上面图的效果,你会怎么开发了?可以下发评论说说你的想法。今天就来看看纯CSS是如何实现这个效果的。
HTML
<div class="radio-stars"> <input class="sr-only" id="radio-5" type="radio" name="radio-star" value="5" /> <label class="radio-star" for="radio-5">5</label> <input class="sr-only" id="radio-4" type="radio" name="radio-star" value="4" checked="checked" /> <label class="radio-star" for="radio-4">4</label> <input class="sr-only" id="radio-3" type="radio" name="radio-star" value="3" /> <label class="radio-star" for="radio-3">3</label> <input class="sr-only" id="radio-2" type="radio" name="radio-star" value="2" /> <label class="radio-star" for="radio-2">2</label> <input class="sr-only" id="radio-1" type="radio" name="radio-star" value="1" /> <label class="radio-star" for="radio-1">1</label> <span class="radio-star-total"></span> </div>
radio-stars是容器,radio-star和sr-only一 一对应,默认是 4 颗星,radio-star-total展示当前星数/总星数。
下面就是重头戏了
css
.radio-stars { display: inline-block; position: relative; unicode-bidi: bidi-override; direction: rtl; counter-reset: star-rating; font-size: 0; } .radio-stars:hover .radio-star::before { content: "☆"; } .radio-stars:hover .radio-star:hover::before, .radio-stars:hover .radio-star:hover ~ .radio-star::before { content: "★"; } .radio-star { display: inline-block; overflow: hidden; cursor: pointer; padding: 0 2px; width: 0.7em; direction: ltr; color: #1199ff90; font-size: 40px; white-space: nowrap; } .radio-star::before { content: "☆"; } .radio-star:hover, .radio-star:hover ~ .radio-star, input:checked ~ .radio-star { color: #1199ff; } input:checked ~ .radio-star { counter-increment: star-rating; } input:checked ~ .radio-star::before { content: "★"; } .radio-star-total { pointer-events: none; direction: ltr; unicode-bidi: bidi-override; position: absolute; right: -2em; bottom: 0.5em; color: gray; color: white; font-size: 20px; } .radio-star-total::before { content: counter(star-rating) "/5"; } .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; margin: -1px; padding: 0; clip: rect(0, 0, 0, 0); border: 0; } html { display: flex; justify-content: center; align-items: center; background: #f577a8; height: 100%; }
主要用到content、counter、counter-increment、counter-reset等属性。
说明
兼容性
counter描述
插入计数器。
在CSS2.1中counter()只能被使用在content属性上。
如果想重复多次计数器可以使用 counters()
counter-increment描述
counter-increment 属性设置某个选取器每次出现的计数器增量。默认增量是 1
如果使用了 “display: none”,则无法增加计数。如使用 “visibility: hidden”,则可增加计数。
公告
喜欢小编的点击关注,了解更多知识!
源码地址请点击下方“了解更多”