2014-03-01 82 views
0

我有2個寬度變化的容器。在他們裏面,我有可點擊的元素。點擊一個容器時,它將調整動畫大小。我想做到這一點,當點擊一個可點擊的元素時,它的容器調整大小並滾動到單擊的元素。下面是一個小提示:http://jsfiddle.net/w7H3M/1/JQuery ScrollTop在動畫中間嗎?

但是,由於調整大小,它滾動到錯誤的位置。以下是點擊事件處理程序:

<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); 
}); 

回答

0

實際上,由於動畫效果不佳,它無法正常工作。當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); 
    }); 


}); 

});