>当我将鼠标悬停在图像上时,我想向右移动一些文本:
<div class="container-fluid">
<div class="info-over">
<div class="infoText">
Text that need to move to the right
</div>
<img src="http://lorempixel.com/300/200" alt="Avatar" class="image">
</div>
</div>
我希望 div infoText
在我悬停图像时缓慢地向右移动50px
,并且当我停止悬停图像时,它会缓慢向后移动。
尝试过过渡,但它对我不起作用,也许你们可以帮忙?
您可以使用
Flexbox、定位、order
属性和相邻的同级组合器 ( +
( 来定位.infoText
div:
.info-over {
display: inline-flex; /* takes only the content's width */
flex-direction: column; /* stacks flex-items (children) vertically */
}
.infoText {
order: -1; /* places the text above the img to achive the same display/layout as before */
position: relative; /* positioned relative to its normal position */
top: 0; /* default */
left: 0; /* default */
transition: left 1s linear; /* adjust */
}
.image:hover + .infoText {
left: 50px;
transition: left 1s linear; /* adjust */
}
<div class="container-fluid">
<div class="info-over">
<img src="http://lorempixel.com/300/200" alt="Avatar" class="image"> <!-- moved it above the text so that you can use the + selector to target the element below -->
<div class="infoText">Text that needs to move to the right</div>
</div>
</div>
transform: translateX()
的另一种方式:
.info-over {
display: inline-flex;
flex-direction: column;
}
.infoText {
order: -1;
transition: transform 1s linear;
}
.image:hover + .infoText {
transform: translateX(50px);
transition: transform 1s linear;
}
<div class="container-fluid">
<div class="info-over">
<img src="http://lorempixel.com/300/200" alt="Avatar" class="image"> <!-- moved it above the text so that you can use the + selector to target the element below -->
<div class="infoText">Text that needs to move to the right</div>
</div>
</div>
但我建议您使用第一种解决方案。
尝试
$(".image").hover(function(){
$(this).closest('div').find('.infoText').animate({
'marginLeft': '+=100px'
}, 500);
}, function(){
$(this).closest('div').find('.infoText').animate({
'marginLeft': '-=100px'
}, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div class="info-over">
<div class="infoText">
Text that need to move to the right
</div>
<img src="http://lorempixel.com/300/200" alt="Avatar" class="image">
</div>
</div>
也添加正确的 CSS。解决方案有点重复,但有效!