繁体   English   中英

jQuery ScrollTop在动画的中间吗?

[英]JQuery ScrollTop in the middle of an animation?

我有2个宽度发生变化的容器。 在他们里面,我有可点击的元素。 单击容器时,它将在动画中调整大小。 我想这样做,以便在单击clickable元素时,其容器会调整大小并滚动到clicked元素。 这是一个显示此内容的小提琴: http : //jsfiddle.net/w7H3M/1/

但是,由于调整大小,它滚动到错误的位置。 这是点击的事件处理程序:

<div id=left>...</div>
<div id=right>...</div>

$('#left').on('click', 'a', function () {
    var node = $(this);
    $('#left').animate({
        width: 0.75 * $(document).width()
    }, 800);
    $('#right').animate({
        width: 0.25 * $(document).width()
    }, 800);

    $('body').animate({
        scrollTop: node.offset().top
    }, 800);
});

$('#right').on('click', 'a', function () {
    var node = $(this);
    $('#left').animate({
        width: 0.25 * $(document).width()
    }, 800);
    $('#right').animate({
        width: 0.75 * $(document).width()
    }, 800);

    $('body').animate({
        scrollTop: node.offset().top
    }, 800);
});

实际上,由于动画的原因,它无法正常工作。 当div扩展时,要显示在屏幕顶部的节点的偏移量将更改。 为了实现所需的效果,您需要在动画完成时设置scrollTop属性。 您可以使用jQuery.animate()的完整处理程序来实现此目的。 我已将您的jsfiddle分叉给您看。 唯一的问题是两个动画现在一个接一个地播放,而不是同时播放。

$(document).ready(function () {
// generate content
var str = '';
for (i = 1; i < 100; i++) {
    str += '<p>' + x100(i) + '</p>';
}
$('#left').html(str);
$('#right').html(str);
// end generate content

$('#left').on('click', 'p', function () {
    var node = $(this);
    $('#left').animate({
        width: 0.75 * $(document).width(),
    }, 800, 'swing', function() {
        $('body, html').animate({scrollTop: node.offset().top}, 800);
    });
    $('#right').animate({
        width: 0.25 * $(document).width()
    }, 800);


});

$('#right').on('click', 'p', function () {
    var node = $(this);
    $('#left').animate({
        width: 0.25 * $(document).width()
    }, 800);
    $('#right').animate({
        width: 0.75 * $(document).width()
    }, 800, 'swing', function() {
        $('body, html').animate({scrollTop: node.offset().top}, 800);
    });


});

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM