我目前正在尝试将一个正方形变成 4 个大小相等且具有悬停事件的三角形。
我正在创建这样的三角形,
.right, left, .top, .bottom {
position: relative;
width: 26px;
}
.right:before{
position: absolute;
display: inline-block;
border-top: 26px solid transparent;
border-right: 26px solid #eee;
border-bottom: 26px solid transparent;
left: 26px;
top: 0px;
content: '';
}
我发现每个三角形都位于另一个三角形之上,这意味着只有一个三角形可以悬停,这是我的示例,
http://codepen.io/anon/pen/qdmbKz http://codepen.io/anon/pen/qdmbKz
正如您所看到的,只有底部三角形(悬停在正方形底部)是可悬停的。我究竟做错了什么?有更好的方法吗?
正如您在问题中已经指出的,原因是hover
仅适用于底部三角形,而不适用于其他三角形,因为底部三角形的容器放置在其他三个三角形的容器的顶部。
当使用边框技巧生成三角形时,实际形状仍然是正方形。它之所以呈现三角形外观只是因为其他三个边框是透明的。现在,当您将鼠标悬停在形状上时,您实际上悬停在底部三角形的透明区域,而不是其他三角形的容器,这就是为什么它们各自的原因hover
事件不会被触发。
我个人建议使用 SVG 来处理这些类型的事情,但使用 CSS 实现形状也不是那么复杂。
SVG:
在 SVG 中,您可以使用polygon
元素在正方形内创建四个三角形,每个三角形polygon
可以单独悬停。如果它们应该有自己的目标链接,您还可以将多边形包含在a
(锚)标签。
In the snippet, I have implemented the anchor only for one triangle
.square {
height: 400px;
width: 400px;
overflow: hidden;
}
svg {
height: 100%;
width: 100%;
}
polygon {
fill: aliceblue;
stroke: crimson;
stroke-linejoin: round;
}
polygon:hover {
fill: cornflowerblue;
}
<div class='square'>
<svg viewBox='0 0 100 100'>
<a xlink:href='http://google.com'>
<polygon points='5,5 50,50 95,5' />
</a>
<polygon points='5,5 50,50 5,95' />
<polygon points='5,95 50,50 95,95' />
<polygon points='95,5 50,50 95,95' />
</svg>
</div>
CSS:
这是对发布的答案的改编here https://stackoverflow.com/questions/23107646/how-can-i-maintain-proper-boundaries-on-css-triangles-when-hovering-with-cursor由网络蒂基。我发布一个单独的答案,因为这个问题的形状要简单得多,并且不需要像另一个问题那样多的工作。
使用以下方法将正方形分成四个大小相等的可悬停三角形:
- 该容器是一个正方形,其所有边都有边框。父级上需要边框,因为使用 CSS 实现三角形上的对角线要困难得多。
- 将四个子元素添加到容器中,其高度和宽度使用毕达哥拉斯定理计算。然后将它们定位,使其左上角位于正方形的中心点(以帮助旋转)。
- 所有子元素都旋转适当的角度以形成三角形。这
transform-origin
被设置为top left
以父方块的中心点为轴进行旋转。
- 家长有
overflow: hidden
以防止每个方块的另一半可见。
- 请注意,向 4 个三角形添加文本并不简单,因为它们也会旋转。文本必须放置在必须反向旋转的子元素内。
Note: The script included in the demo is the prefix free library which is used to avoid browser prefixes.
.square {
position: relative;
height: 200px;
width: 200px;
border: 2px solid crimson;
overflow: hidden;
transition: all 1s;
}
.top,
.left,
.right,
.bottom {
position: absolute;
height: calc(100% / 1.414);
width: calc(100% / 1.414);
top: 50%;
left: 50%;
border: 1px solid crimson;
transform-origin: 0% 0%;
}
.right {
transform: rotate(-45deg);
}
.bottom {
transform: rotate(45deg);
}
.top {
transform: rotate(-135deg);
}
.left {
transform: rotate(135deg);
}
.square > div:hover {
background: tomato;
}
/*Just for demo*/
.square:hover{
height: 300px;
width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='square'>
<div class="top"></div>
<div class="right"></div>
<div class="bottom"></div>
<div class="left"></div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)