保证金变更事件

时间:2012-09-10 19:55:14

标签: javascript jquery events scroll margin

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

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

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

2 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

你的意思是这样吗?

我有与Alex 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/