当用户手动更改滚动位置时,如何在ajax定时器异步回发期间停止保持滚动位置?

时间:2013-04-04 12:47:33

标签: javascript asp.net ajax c#-4.0

我使用异步回发将多行文本框用作聊天窗口。我能够保持滚动位置,但是当用户正在阅读聊天消息时,文本框会自动滚动到最底部。我能够保持用户所处的位置或使其自动向下滚动。但是,我想做两件事。

这是我的代码:

var prm = Sys.WebForms.PageRequestManager.prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler); 
function BeginRequestHandler(sender, args) { 
  xPos = $get('txtChatBox').scrollLeft; 
  yPos = $get('txtChatBox').scrollTop; 
  zpos =$get('txtChatBox').scrollHeight; 
} 

function EndRequestHandler(sender, args) { 
  $get('txtChatBox').scrollLeft = xPos + 1; 
  $get('txtChatBox').scrollTop = yPos + 1; 
  $get('txtChatBox').scrollTop =zpos+1; 
}

有人可以帮助我吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用scroll event来检测用户是否已手动滚动。

var xPos, yPos, hasScrolled, timer, box = $get('txtChatBox');
box.onscroll = function(e) {
  hasScrolled = true;
  /* if you want to invalidate the flag after the user has not scrolled
     for a certain period, use
  clearTimeout(timer);
  timer = setTimeout(function() {
    hasScrolled = false;
  }, 60000) // 1 min for example
  */
};
function BeginRequestHandler(sender, args) { 
  xPos = box.scrollLeft; 
  yPos = box.scrollTop;
  zPos = box.scrollHeight;
  hasScrolled = false;
}
function EndRequestHandler(sender, args) {
  if (!hasScrolled) {
    box.scrollLeft = xPos + 1; 
    box.scrollTop = zPos+1;
  }
}

或者您只是将存储的scrollTop(yPos)与当前的scrollTop进行比较,以检测用户是否滚动(而不是向后):

function EndRequestHandler(sender, args) {
  if (box.scrollTop == yPos) {
    box.scrollLeft = xPos + 1; 
    yPos = box.scrollTop = zPos+1;
  }
}