你可以在CSS中使用“hover”选择器和“nth-of-type”来实现这一点。
选择每三行中的元素:
:nth-of-type(3), :nth-of-type(7), :nth-of-type(13), :nth-of-type(15)
和第四行:
:nth-of-type(4), :nth-of-type(8), :nth-of-type(12), :nth-of-type(16)
并给它的弹出框添加必要的属性。
演示:http://dabblet.com/gist/3765761
标记:
<div class='box'>1
<div class='fly-out'></div>
</div>
<div class='box'>2
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>3
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>4
<div class='fly-out'></div>
</div>
<div class='box'>5
<div class='fly-out'></div>
</div>
<div class='box'>6
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>7
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>8
<div class='fly-out'></div>
</div>
<div class='box'>9
<div class='fly-out'></div>
</div>
<div class='box'>10
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>11
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>12
<div class='fly-out'></div>
</div>
<div class='box'>13
<div class='fly-out'></div>
</div>
<div class='box'>14
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>15
<div class='fly-out'></div>
</div>
<div class='box right-aligned'>16
<div class='fly-out'></div>
</div>
CSS:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
position: relative;
}
body {
width: 440px;
margin: 0 auto;
}
.box {
width: 100px;
height: 100px;
border: 1px solid #999;
float: left;
margin: 5px;
}
.fly-out {
position: absolute;
top: 0;
background: rgba(0,0,0,.4);
opacity: 0;
z-index: -1;
}
.box:hover .fly-out {
z-index: 1;
opacity: 1;
height: 100%;
width: 210px;
}
.box:nth-of-type(3):hover .fly-out,
.box:nth-of-type(7):hover .fly-out,
.box:nth-of-type(11):hover .fly-out,
.box:nth-of-type(15):hover .fly-out,
.box:nth-of-type(4):hover .fly-out,
.box:nth-of-type(8):hover .fly-out,
.box:nth-of-type(12):hover .fly-out,
.box:nth-of-type(16):hover .fly-out,
.right-aligned {
left: -110px;
right: 0;
background: rgba(0,0,120,.7);
}
在您的标记中,“工具提示”位于框外,并且具有“visibility: hidden”,这几乎就像给它“opacity: 0”。虽然看不见,但它仍然存在。要使其实际上无法使用布局,您需要“display: none”,但是这样您将无法使用CSS过渡正确地对其进行动画处理。
注意:如下面评论中所提到的Christofer Eliason,':nth-of-type'选择器支持不太好,因此您可以为要右对齐飞出的每个div添加一个类,或者查看使用“nth-of-type”的jquery版本:
https://dev59.com/VHI95IYBdhLWcg3w7CjL#4761510。
我使用了':nth-of-type'选择器,因为您可以从CSS本身控制飞出的对齐方式,而无需为新框添加类(如果它们是动态添加的),这可能对我来说有点复杂数学上的问题。
但是,如果您对此感到满意,我已经向第三行和第四行的框中添加了一个类'.right-aligned',您可以在CSS中删除此块,您仍然很好:
.box:nth-of-type(3):hover .fly-out,
.box:nth-of-type(7):hover .fly-out,
.box:nth-of-type(11):hover .fly-out,
.box:nth-of-type(15):hover .fly-out,
.box:nth-of-type(4):hover .fly-out,
.box:nth-of-type(8):hover .fly-out,
.box:nth-of-type(12):hover .fly-out,
.box:nth-of-type(16):hover .fly-out