可以使用:hover
伪类结合:before
或:after
伪元素来实现。首先,在需要判断鼠标进入方向的元素上添加一个:before
或:after
伪元素,用来作为指示物(arrow),通过设置其大小和位置来实现方向指示。然后,使用transform
和transition
属性来实现过渡效果。最后,结合:hover
伪类和鼠标在元素上的位置,利用伪元素的绝对定位和样式变化,实现判断鼠标进入方向的效果。
以下是一个示例代码:
HTML:
<div class="box"></div>
CSS:
.box { position: relative; width: 200px; height: 200px; background-color: lightgreen; } .box:hover:before { content: ''; position: absolute; width: 0; height: 0; border-width: 10px; border-style: solid; border-color: transparent; transition: all 0.2s ease-out; } /* 鼠标从左边进入 */ .box:hover:before { left: 0; top: 50%; margin-top: -10px; border-right-color: lightgray; } /* 鼠标从右边进入 */ .box:hover:before { right: 0; top: 50%; margin-top: -10px; border-left-color: lightgray; } /* 鼠标从上边进入 */ .box:hover:before { top: 0; left: 50%; margin-left: -10px; border-bottom-color: lightgray; } /* 鼠标从下边进入 */ .box:hover:before { bottom: 0; left: 50%; margin-left: -10px; border-top-color: lightgray; }
可以根据需要自行调整指示物的大小、颜色和过渡时间等属性。