鼠标悬停mouseleave translateY不重复

时间:2016-12-04 19:30:09

标签: jquery html css

我试图在jquery中使用一个函数,我使用mouseover从顶部显示div,而mouseleave使它消失。我能够做到这一次,但是如果我再次进行鼠标移除则不再有效。

HTML

<div id="box">
<div id="box_appear"></div>
</div>

CSS

#box{position:relative; width:300px; height:300px; overflow:hidden}
#box_appear{position:absolute; width:300px; height:300px; transform:translateY(-100%); top:0;left:0}

@keyframes slideInDown {
from {
-webkit-transform: translate3d(0, -100%, 0);
transform: translate3d(0, -100%, 0);
visibility: visible;
}

to {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
  }
 }

.slideInDown {
 -webkit-animation-name: slideInDown;
 animation-name: slideInDown;
 -webkit-animation-duration: 0.5s;
 animation-duration: 0.5s;
 -webkit-animation-fill-mode: both;
 animation-fill-mode: both;
}

@keyframes slideInUp {
from {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
visibility: visible;
}

to {
-webkit-transform: translate3d(0, -100%, 0);
transform: translate3d(0, -100%, 0);
}
}

.slideInUp {
-webkit-animation-name: slideInUp;
animation-name: slideInUp;
-webkit-animation-duration: 0.5s;
animation-duration: 0.5s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}

jquery的

$('#box').on('mouseover', function () {

   $('#box_appear').addClass('slideInDown');


});
$('#box').on('mouseleave', function () {       
       $('#box_appear').addClass('slideInUp');
});

2 个答案:

答案 0 :(得分:0)

你在两个例程中都AddClass;鼠标悬停在父节点上后,导致内部div以两个类结束。

解决方案:在mouseout例程中使用removeClass,而不是添加第二个类。

答案 1 :(得分:0)

这只是一个优化提示,但由于你多次调用$('$box_appear')我会缓存它以减少查找。你也可以做同样的#or $('#box')

至于您的主要问题您需要删除mouseover/mouseleave上添加的类。否则他们会相互否定:

$box = $('#box');
$boxAppear = $('#box_appear');

$box.on('mouseover', function () {
  $boxAppear
    .removeClass('slideInUp')
    .addClass('slideInDown');
}).on('mouseleave', function() {
  $boxAppear
    .removeClass('slideInDown');
    .addClass('slideInUp');
});