2013-04-30 51 views
0

由於某些原因,此代碼通常會向上/向下滾動到指定的targetDiv的起始位置,而不是滾動頁面的下方,而不是targetDiv已存在的位置。jQuery在動態加載內容後滾動到錯誤的偏移量

function postData(data, url, divAction, targetDiv) { 
    $.ajax({ 
     type: 'POST', 
     url: url, 
     data: data, 
     success: function(response) { 
      if (divAction == 'hide') { 
       $(targetDiv).hide(); 
       $(targetDiv).empty(); 
      } 
      if (divAction == 'refresh') { 
       $(targetDiv).html(response); 
       $('html, body').animate({ 
        scrollTop: '+=' + $(targetDiv).offset().top + 'px' 
       }, 'fast'); 
      } 
     }, 
     error: function() { 
      alert('Error! Plese try again.'); 
     } 
    }); 
    return false; 
}; 

任何建議表示讚賞!

回答

2

而應該試試這個:

$('html, body').animate({ 
    scrollTop: $(targetDiv).offset().top 
}, 'fast'); 
+0

謝謝!這簡單的呃..它可能看起來像我很懶,但我真的試圖解決這個問題,我真的吸吮js! – cianz 2013-04-30 08:56:51

0

這裏是 jsfiddle和它的作品。 `

targetDiv = $('#id1'); 
$(targetDiv).html("<iframe src=\"www.google.com\" />"); 
$('html, body').animate({scrollTop: '+=' + $(targetDiv).offset().top + 'px' 

}, '快')`