Page 51 - JavaScript修炼之道
P. 51
任务17 在载入内容时保持显示区域 39
维持显示区域位置
ui/viewport/index.html
<h2>Comments</h2>
<div id="extraComments">
<a id="loadKnownComments" href="?with_known_comments">See previous
comments you already know about</a>
</div>
<h3>Comment 5</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.</p>
①
在Ajax之前获得滚动位置,在Ajax之后调整
ui/viewport/viewport.js
function loadKnownComments(e) {
e.stop();
var zone = $('extraComments'), ref = zone.next('h3');
var upd = new Ajax.Request('known_comments.html', {
method: 'get',
onSuccess: function(res) {
var orig = ref.cumulativeOffset().top -
document.viewport.getScrollOffsets().top;
zone.insert({ before: res.responseText });
window.scrollTo(0, ref.cumulativeOffset().top - orig);
}
});
}
——————————
① 此处代码的意思是“进行Ajax请求,在插入新内容之前获得滚动位置,并在插入之后恢复位置”。*