使用纯CSS实现元素框选状态

Yukino 446 2021-12-29

我们使用Visio、OmniGraffle、Process On等这些画图软件时,点击一个元素会出现几个小圆圈和一个方框,表示这个元素目前是选中的一个状态,最近项目中也要做类似的效果,就查了查相关的内容,记录下两种实现方式:

一、添加div

这种方法很好理解,就是把一个元素放在一个新的div中,同时添加8个新的div,将新的div的样式设置成小圆圈,然后用绝对定位设置在对应的位置即可,就不在这赘述,可以参考这篇博客Making a resizable div in JS is not easy as you think | by Nguyễn Việt Hưng | The happy lone guy | Medium,这篇博客也讲了如何让一个div变得可以通过拖动改变大小,讲的还是蛮清楚的(不过medium需要科学上网)。

二、纯CSS实现

在项目中其实已经实现了通过拖动改变div的大小,所以新的需求只是需要一个框选的样式,在以考虑改动最小的情况下,想了想能否有纯CSS的实现,查了下资料还真有,先来看看效果:
20450286af27bb5e82730304.png
在线效果可以看看这个https://codepen.io/yukino_yukino/pen/abmrvKG
下面来看看代码:

<div class="box"></div>
.box {
  position: relative;
  width: 100px;
  height: 100px;
  background-color: white;
  margin: 50px auto;
  border: 1px solid #000;
}

.box::before {
  content: "";
  position: absolute;
  height: calc(100% + 10px);
  width: calc(100% + 10px);
  top: -5px;
  left: -5px;
  background-image: 
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff),
    linear-gradient(#45aeff, #45aeff);
  background-size: 10px 10px;
  background-position: top left, bottom left, center left, top center, bottom center, top right, center right, bottom right;
  background-repeat: no-repeat;
}

body {
  background-color: #bbb;
}

原理其实很简单,就是利用border描框,利用::before (:before) - CSS(层叠样式表) | MDN伪类来的background-image描绘8个方块,然后用background-position将8个方块放置到对应位置,这里的background-image是直接使用的色块,也可以根据需要设计成圆形,亦或者可以直接使用图片。
不过这种方式有个缺陷,它无法像第一种方法那样设置指针的样式,也就是在鼠标悬浮在方块上时,不会变成可resize的样式(指针样式可参考cursor-MDN)。

参考文章:
[1][Making a resizable div in JS is not easy as you think | by Nguyễn Việt Hưng | The happy lone guy | Medium](https://medium.com/the-z/making-a-resizable-div-in-js-is-not-easy-as-you-think-bda19a1bc53d).
[2][css shapes - CSS: dots in corners of div - Stack Overflow](https://stackoverflow.com/questions/20964278/css-dots-in-corners-of-div).
[3][::before (:before) - CSS(层叠样式表) | MDN](https://developer.mozilla.org/zh-CN/docs/Web/CSS/::before).
[4][background-image - CSS(层叠样式表) | MDN](https://developer.mozilla.org/zh-CN/docs/Web/CSS/background-image).


# CSS # 前端