如何添加jQuery scrollTop偏移量?

use*_*219 3 javascript jquery

我正在尝试使div捕捉到视口的中心,现在它只是捕捉到顶部。我试图将偏移量设置为50%,但只能以px为单位。

编辑

我在其中尝试添加一个新的小提琴 $(window).scrollTop() / 2)

http://jsfiddle.net/kZY9R/84/

$("#item").offset().top - 100

var body = $("html, body");
var items = $(".item");
var animating = false;

$(window).scroll(function() {
    clearTimeout($.data(this, 'scrollTimer'));
    if (!animating) {
        $.data(this, 'scrollTimer', setTimeout(function() {

            items.each(function(key, value) {
                if ($(value).offset().top > $(window).scrollTop()) {
                    animating = true;
                    $(body).stop().animate( { scrollTop: $(value).offset().top }, 1000,'swing');
                    setTimeout(function() { animating = false; }, 2000);
                    return false;
                }
            });
        }, 50));
    }
});
Run Code Online (Sandbox Code Playgroud)

osa*_*ger 5

我找到了这个:

$('html, body').animate({scrollTop: $('#your-id').offset().top -100 }, 'slow');
Run Code Online (Sandbox Code Playgroud)

来源:运行ScrollTop并使用ID偏移元素

  • 所以我现在明白了。http://jsfiddle.net/kZY9R/81/我仍然需要添加一个边距或其他一些东西来使其距顶部的一半。这也只能使其距顶部100像素不成百分数。 (2认同)