我們使用Visio、OmniGraffle、Process On等這些畫(huà)圖軟件時(shí),點(diǎn)擊一個(gè)元素會(huì)出現(xiàn)幾個(gè)小圓圈和一個(gè)方框,表示這個(gè)元素目前是選中的一個(gè)狀態(tài),最近項(xiàng)目中也要做類(lèi)似的效果,就查了查相關(guān)的內(nèi)容,記錄下兩種實(shí)現(xiàn)方式:
一、添加div
這種方法很好理解,就是把一個(gè)元素放在一個(gè)新的div中,同時(shí)添加8個(gè)新的div,將新的div的樣式設(shè)置成小圓圈,然后用絕對(duì)定位設(shè)置在對(duì)應(yīng)的位置即可,就不在這贅述,可以參考這篇博客Making a resizable div in JS is not easy as you think | by Nguy?n Vi?t H?ng | The happy lone guy | Medium,這篇博客也講了如何讓一個(gè)div變得可以通過(guò)拖動(dòng)改變大小,講的還是蠻清楚的(不過(guò)medium需要科學(xué)上網(wǎng))。
二、純CSS實(shí)現(xiàn)
在項(xiàng)目中其實(shí)已經(jīng)實(shí)現(xiàn)了通過(guò)拖動(dòng)改變div的大小,所以新的需求只是需要一個(gè)框選的樣式,在以考慮改動(dòng)最小的情況下,想了想能否有純CSS的實(shí)現(xiàn),查了下資料還真有,先來(lái)看看效果:

在線(xiàn)效果可以看看這個(gè)https://codepen.io/yukino_yukino/pen/abmrvKG
下面來(lái)看看代碼:
<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;
}
原理其實(shí)很簡(jiǎn)單,就是利用border描框,利用::before (:before) - CSS(層疊樣式表) | MDN偽類(lèi)來(lái)的background-image描繪8個(gè)方塊,然后用background-position將8個(gè)方塊放置到對(duì)應(yīng)位置,這里的background-image是直接使用的色塊,也可以根據(jù)需要設(shè)計(jì)成圓形,亦或者可以直接使用圖片。
不過(guò)這種方式有個(gè)缺陷,它無(wú)法像第一種方法那樣設(shè)置指針的樣式,也就是在鼠標(biāo)懸浮在方塊上時(shí),不會(huì)變成可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.
[2]css shapes - CSS: dots in corners of div - Stack Overflow.
[3]::before (:before) - CSS(層疊樣式表) | MDN.
[4]background-image - CSS(層疊樣式表) | MDN.