2012-09-10 43 views
0

我有一个带有顶部边距动画的元素。我需要检测它是否离边界太近,如果是,请将父div移动到较低的位置,以防止隐藏动画元素。这里有一个例子:保证金变化事件

http://jsfiddle.net/zYYBR/5/

这个绿色的盒子不应该是红色的线下点击“向下”按钮后。

+0

? –

+0

这个元素的右侧滚动(#容器)。 – ciembor

+0

不知道你在做什么。为什么即使有一个可滚动的div?如果您只是想让绿框向下移动,直到它碰到红线然后停止,为什么不使用position:relative并更改顶部样式元素,当top + width> =行的媒体框顶部时停止? –

回答

1

你的意思是?

var new_margin; 
var step = 75; 
var limit = $("#max")[0].offsetTop; 

$('#down').click(function() { 
    var goStep = step; 
    var elHeight = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight;  
    if((elHeight + step) > limit) 
    { 
     goStep = limit - elHeight; 
    } 
    new_margin = goStep + parseInt($('#animated').css('margin-top')); 
    $("#animated").animate({marginTop: new_margin}, 1000); 
}); 

http://jsfiddle.net/zYYBR/8/

编辑:或者,也许类似的东西(当然你也可以提高计算,因为目前这是非常错误与滚动):

var new_margin; 
     var step = 75; 
     $('#down').click(function() { 
      scroll(1000); 
     }); 

     var scrollTimer = null; 
     $("#container").bind("scroll", function() { 
      clearTimeout(scrollTimer); 
      scrollTimer = setTimeout(function() { scroll(1); }, 10); 
     }); 

     function scroll(speed) { 
      var scrollStep, animationStep = step; 
      var currentBoxBottom = $("#animated")[0].offsetTop + $("#animated")[0].offsetHeight; 
      var nextCurrentBoxBottom = currentBoxBottom + step; 
      var limit = $("#max")[0].offsetTop + $("#container")[0].scrollTop; 
      if (nextCurrentBoxBottom > limit) { 
       if (limit >= $("#container")[0].scrollTop) { 
        scrollStep = $("#container")[0].scrollTop + nextCurrentBoxBottom - limit; 
       } 
       else { 
        scrollStep = $("#container")[0].scrollTop - nextCurrentBoxBottom - limit; 
        animationStep = nextCurrentBoxBottom - limit; 
       } 

       $("#container")[0].scrollTop = scrollStep; 
      } 

      new_margin = animationStep + parseInt($('#animated').css('margin-top')); 
      $("#animated").animate({ marginTop: new_margin }, speed); 
     } 

http://jsfiddle.net/zYYBR/13/

+0

不是。绿框应该放下(相对于#inner),每按一下相同的距离。但#container应该向下滚动,当它位于红线下方时。 – ciembor

+0

@ciembor看我的编辑。 –

0

你的意思是这样吗?

我和亚历克斯Dn有相同的视觉效果,但是我为我想说的话增加了一点额外的方向。如果这是你要找的,我会进行更新:

var new_margin; var step = 75; var limit = $(“#max”)[0] .offsetTop;

$('#down2').click(function() { 
var anim = $("#animated"); 
var hrOff = $("#max").offset(); 
var thOff = anim.offset(); 
new_margin = Math.min(hrOff.top - thOff.top - anim.height(), 75); 
console.log(new_margin, hrOff.top, thOff.top); 
var st = 0; 
if (new_margin < 75) { 
    st = 75 - new_margin; 
    //have container scroll by this much? 
} 

anim.animate({ 
    marginTop: "+=" + new_margin 
}, 1000); 
});​ 

http://jsfiddle.net/zYYBR/10/

当你说滚动的父母,你在你的例子指的是什么元素
+0

不是。滚动仍然不移动(并且箱子不会相对于#inner下降)。 – ciembor

+0

@Alex Dn和ciembor我很抱歉 - 在我尝试使用它之前,我无意中发布了Alex的代码。我用正确的代码更新了我的帖子,jsFiddle从一开始就是正确的。对不起,再次 –

+0

@ciembor,我知道这个窗口实际上并没有滚动 - 我只是在代码中用一个小草稿扔掉了这个注释,以便让我的问题跨越:这就是你要找的东西,也就是说,像我开始写的东西这使容器滚动额外的金额?我可以帮你编码,但我不想浪费时间,如果这不是你想要的 –