这是一个用于说明目的的小提琴: http://jsfiddle.net/wVRtL/
HTML:
<section class="full-w blue">
<div class="container">
<div class="three"></div>
<div class="two"></div>
</div>
</section>
<section class="full-w red">
<div class="container">
<div class="two"></div>
<div class="three"></div>
</div>
</section>
的jQuery
$('.full-w').hover(function() {
marginTopHero = $(this).find('.two').css("margin-top").replace("px", "");
newMargin = marginTopHero - 50 + "px";
oldMargin = marginTopHero + "px";
$(this).find('.two').stop().animate({ 'margin-top': newMargin }, 'fast');
}, function() {
$(this).find('.two').stop().animate({ 'margin-top': oldMargin }, 'fast');
});
预期的行为是,当悬停在线上时,黄色矩形向上移动,并在鼠标离开线时向下移动到其原始位置。但是如果你将指针从一条红线快速移动到另一条红线,你会看到黄色框逐渐抬起,直到它撞到线的顶部。
我必须检索此元素的margin-top值才能恢复到mouseleave上的那个位置(margin-top将从一个.two变为另一个)
我知道这很棘手,除非我完全错过了什么。
谢谢!
答案 0 :(得分:1)
问题可能在于您将旧值保存在共享的全局变量中,请使用.data() api来保存以前的valud
$('.full-w').hover(function() {
var marginTopHero = $(this).find('.two').css("margin-top").replace("px", "");
var newMargin = marginTopHero - 150 + "px";
$(this).data('oldMargin', marginTopHero + "px")
$(this).find('.two').stop().animate({ 'margin-top': newMargin }, 'fast');
}, function() {
$(this).find('.two').stop().animate({ 'margin-top': $(this).data('oldMargin') }, 'fast');
});