我总共有 3 个 div。 总是出现一个div,当鼠标进入div1时会出现剩余的两个div。这是一个使用 jQuery 的演示。
Demo使用 jQuery
但是它没有正常工作。 当鼠标在动画完成之前进入/离开时会给出错误的功能。所以我尝试使用 CSS3,但动画无法正常工作。使用 CSS 进行演示。
Demo使用 CSS
代码如下:
HTML:
<div class='holder'>
<div class="menu" id="m1"></div>
<div class="menu" id="m2"></div>
<div class="menu" id="m3"></div>
</div>
CSS:
.menu {
top:10px;
margin: 0;
padding:0px;
width: 40px;
height:40px;
border-radius: 100%;
display: inline-block;
background-color: #34495e;
transition: 1s;
position: absolute;
}
#m1 {
z-index: 1000;
}
#m2, #m3 {
z-index: 1;
}
.menu:hover {
background-color: #3498db;
}
.menu:hover ~ div:nth-child(3n), .menu:hover ~ div:nth-child(2n){
position:relative;
left: 50px;
margin-left: 10px;
}
如何解决这个问题?如何使用适当的动画和鼠标事件移动 div?
最佳答案
与其进行计算以移除您添加的 margin 量,不如将其设置回 0。
这使用了 jQuery 方法。
$(document).ready(function() {
$('#m2').hide();
$('#m3').hide();
$('#m1').one('mouseenter', function() {
$('#m2').show();
//$('#m2').addClass('show');
$('#m2').animate({
'marginLeft': "+=45px" //moves right
});
$('#m3').show();
//$('#m2').addClass('show');
$('#m3').animate({
'marginLeft': "+=90px" //moves right
});
});
$('.holder').mouseleave(function() {
$('#m3').animate({
'marginLeft': "0px" // sets margin back to 0
});
$('#m2').animate({
'marginLeft': "0px" // sets margin back to 0
});
});
});
.menu {
top: 10px;
margin: 0;
padding: 0px;
width: 40px;
height: 40px;
border-radius: 100%;
display: inline-block;
background-color: #34495e;
transition: 1s;
position: absolute;
}
#m1 {
z-index: 1000;
}
#m2,
#m3 {
z-index: 1;
}
.holder {
display: block;
}
#m1:hover {
background-color: #3498db;
}
.show {
transition: 1s;
position: relative;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='holder'>
<div class="menu" id="m1"></div>
<div class="menu" id="m2"></div>
<div class="menu" id="m3"></div>
</div>
关于javascript - 移动 div 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29366861/