如何实现hover时child元素沿parent容器长度滑动?
实现自适应父容器宽度的滑块效果
需求说明
需要制作一个CSS滑块,让child元素能沿parent容器的长度滑动,无论parent容器的宽度是多少(当前设置为22%),且hover状态下child元素保持静止,不会来回晃动。
首次尝试代码
该方案无法满足需求,因为transform: translateX(100%)是让子元素向右移动自身宽度的100%,而非父容器的宽度:
CSS
div.parent { position: absolute; display: block; width: 22%; height: 60px; background: #333; color: white; cursor: pointer; margin: 10px; overflow: hidden; min-width: 60px; max-width: 30%; } div.child { position: absolute; height: 60px; width: 60px; background-color: #888; z-index: 0; color: #333; text-align: center; line-height: 60px; font-size: 40px; transition: .5s; } div.parent:hover div.child { transform: translateX(100%); background: orange; color: #fff; }
HTML
<div class="slider-container"> <div class="parent"> <div class="child"> </div> </div> </div>
存在晃动问题的JSFiddle方案
该方案通过新增child-wrapper实现位移,但鼠标在parent内移动时,child元素会来回晃动:
CSS
div.parent { position: absolute; display: block; width: 22%; height: 60px; background: #333; color: white; cursor: pointer; margin: 10px; overflow: hidden; min-width: 60px; max-width: 30%; } div.child-wrapper{ position: absolute; width: 100%; height: 100px; transition: all .5s; z-index: 1; background: #333; } div.child { position: absolute; height: 60px; width: 60px; background-color: #888; transition: inherit; z-index: 0; color: #333; text-align: center; line-height: 60px; font-size: 40px; } div.child-wrapper:hover { transform: translateX(100%); background: orange; } div.child-wrapper:hover div.child { transform: translateX(-100%); background: orange; color: #fff; }
HTML
<div class="slider-container"> <div class="parent"> <div class="child-wrapper"> <div class="child"> </div> </div> </div> </div>
优化后的解决方案
该方案将hover事件绑定在父容器上,避免状态反复切换,同时用calc()精准计算位移距离,确保child元素沿父容器长度滑动且hover时保持静止:
CSS
div.parent { position: absolute; display: block; width: 22%; height: 60px; background: #333; color: white; cursor: pointer; margin: 10px; overflow: hidden; min-width: 60px; max-width: 30%; } div.child { position: absolute; height: 60px; width: 60px; background-color: #888; z-index: 0; color: #333; text-align: center; line-height: 60px; font-size: 40px; transition: transform 0.5s ease; transform: translateX(0); } div.parent:hover div.child { /* 位移距离 = 父容器宽度 - 子元素宽度,确保滑到父容器最右侧 */ transform: translateX(calc(100% - 60px)); background: orange; color: #fff; }
HTML
<div class="slider-container"> <div class="parent"> <div class="child"> </div> </div> </div>
问题原因说明
之前的JSFiddle方案晃动是因为hover事件绑定在child-wrapper上,当它向右移出父容器可视区域后,鼠标会失去hover触发,元素恢复原位;恢复后又重新触发hover,如此循环导致晃动。将hover绑定在位置固定的parent容器上,就能稳定保持hover状态。
内容的提问来源于stack exchange,提问作者Crimp
相关产品推荐
相关产品推荐

