【发布时间】:2021-06-29 13:38:51
【问题描述】:
当我们将鼠标悬停在当前 div 上时,我想移动伪元素。这里粉红色的 div 我想在当前悬停的 div 前面垂直移动。任何人都可以向我建议如何实现此输出
$(document).ready(function() {
$(".timeline-entry").hover(function(e) {
e.preventDefault();
$('.timeline-entry.current').removeClass('current');
$(this).addClass('current');
});
});
.timeline {
position: relative;
display: flex;
flex-direction: column;
}
article {
width: 100px;
height: 50px;
background: red;
}
.timeline-entry.right-aligned {
align-self: flex-end;
background: blue;
}
.timeline-entry.left-aligned {
float: left;
}
.timeline:after {
content: '';
position: absolute;
top: 0;
left: 50%;
width: 20px;
height: 50px;
background: pink;
}
/* .timeline-entry:hover .timeline:nth-child(1) .timeline:after {
top: 100px;
} */
.timeline-entry.current {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="timeline">
<article class="timeline-entry right-aligned"></article>
<article class="timeline-entry left-aligned"></article>
<article class="timeline-entry right-aligned"></article>
<article class="timeline-entry left-aligned"></article>
</div>
【问题讨论】:
-
有必要移动那个粉色元素吗?因为如果没有,那么对于每个悬停的 div,只需 CSS 即可轻松完成。
-
@Gil 是的,我想移动:在粉红色元素从上到下之后
-
你不能通过在孩子身上使用 :after 或 :before 来做到这一点吗?根据子位置将其移动到父级上很棘手。我能想到的唯一方法是用js写入样式标签。我只是使用 css
attr()函数做了一些尝试,但它对content以外的属性的支持有限 -
或者让它成为一个真正的dom元素而不是使用
:after?您甚至可以为真实元素制作动画 -
@Husna 问题来了,移动伪元素需要计算其相对于悬停元素的绝对位置,并且会在页面大小发生变化时中断,因此需要添加一个调整大小的监听器.更可靠的解决方案是将其设置为非伪元素并将其作为子元素添加到悬停元素,但如果最终结果在悬停时显示相同的元素,则设置
:after选择器会很好。
标签: javascript html jquery css