0

我有一个带有动画上边距的元素。我需要检测它是否离边框不太近,如果是,将父 div 滚动到较低位置,以防止动画元素隐藏。这是一个例子:

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

单击“向下”按钮后,此绿色框不应低于红线。

4

2 回答 2

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/

于 2012-09-10T20:12:06.673 回答
0

你的意思是这样的吗?

我的视觉结果与 Alex Dn 相同,但我为您所说的内容添加了一些额外的方向。如果这是您要查找的内容,我将进行更新:

var new_margin; 变量步= 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);
});​

​</p>

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

于 2012-09-10T20:21:43.483 回答