公司的设计师痴迷于圆角,所以最近多了一个 button radio 的需求。
![9a5f935910e63bc90d23caa8280d376b.png](https://img-blog.csdnimg.cn/img_convert/9a5f935910e63bc90d23caa8280d376b.png)
乍一看,不就是三个按钮嘛,简单!设置按钮容器定宽,中间的分割线,使用伪类实现。(ps:公司的项目用了 Vue,所以不喜欢 Vue 的只能将就一下了,o(∩_∩)o 哈哈)(pps:我也不喜欢,但是工作嘛)
<div class="btn-group">
<span :class="{ 'achieve-btn': status === 'achieve'}"
@click="chooseStatus('achieve')"
class="status-btn">已达成</span>
<span :class="{ 'current-btn': status === 'current'}"
@click="chooseStatus('current')"
class="status-btn">当前等级</span>
<span :class="{ 'unlock-btn': status === 'unlock'}"
@click="chooseStatus('unlock')"
class="status-btn">待解锁</span>
</div>
CSS 代码
.btn-group {
width: 240px;
border-radius: 8px;
border: 1px solid #e2e2ea;
height: 34px;
font-size: 14px;
& > span:not(:last-child) {
border-right: 1px solid rgba(226,226,234,1);
}
}
.status-btn {
cursor: pointer;
display: inline-block;
color:rgba(105,105,116,1);
line-height:34px;
text-align: center;
width: 80px;
box-sizing: border-box;
&:hover {
color: rgba(255,140,8,1);
}
}
为按钮绑定的点击事件,一点点 JS 代码。
chooseStatus(type) {
if (type === this.status) {
this.status = ''
} else {
this.status = type
}
}
![a324eb32f91bb21512aca918a528f01c.png](https://img-blog.csdnimg.cn/img_convert/a324eb32f91bb21512aca918a528f01c.png)
Outline 方案
还缺了按钮点击后的效果。因为三个按钮都不是真实的,所以不能用 border 了。所以我考虑用 outline 属性。
![2d88359fb479464f3748341bfcd8d7be.png](https://img-blog.csdnimg.cn/img_convert/2d88359fb479464f3748341bfcd8d7be.png)
效果惨不忍睹,圆角刚好落在了边框内。那能不能对 outline 添加 border-radius 属性呢?不好意思,真不可以。那就只能请出万能的伪类了。
伪类
原理:使用 after伪类包围住按钮文字,再添加 border-radius 属性。如何包围文字呢?使用绝对定位。老套路,为 span 元素的 position属性设置 static,伪类设置 absolute。第二步,将伪类的 top, right, botton, left 属性设置为向外偏移一个边框宽度,刚好覆盖容器 . btn-group的边框。
.achieve-btn {
background:rgba(255,246,236,1);
border-radius:8px 0px 0px 8px;
position: relative;
color: rgba(255,140,8,1);
&:after {
content: '';
display: block;
position: absolute;
top: -1px;
bottom: -1px;
left: -1px;
right: -1px;
border-radius: 8px 0px 0px 8px;
border: 1px solid rgba(255,140,8,1);
}
}
第二步,为伪类添加上 border-radius 属性。事情似乎告一段落了。你可能已经发现,按钮本身也被我添加上了 border-radius 属性。为什么?因为如果不添加,背景色的四角会溢出按钮跑到外面去。左侧设置左上和左下,右侧的设置右上和右下。中间的按钮就不用设置了。
![a4a1f982d4fef1742e793e2383f67c10.png](https://img-blog.csdnimg.cn/img_convert/a4a1f982d4fef1742e793e2383f67c10.png)
做完了之后,发现 UI 框架已经有了。泪崩,不过也算练习了自己的 CSS 技巧。如果对这个效果感兴趣的话,点开 code sandbox 练练。
Button Radiocodesandbox.io题图由Free-Photos在Pixabay上发布。
参考:
- stack overflow 上问题「Outline radius?」中mononym 的回答( https://stackoverflow.com/questions/5394116/outline-radius )。