如何在 MVC 中保持滚动位置? [英] How do I maintain scroll position in MVC?

查看:25
本文介绍了如何在 MVC 中保持滚动位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 MVC 中从事一个项目,并且很喜欢了解它.有一些成长的烦恼,但一旦你弄清楚它们就不错了.在 WebForms 世界中,真正简单的一件事是维护页面上的滚动位置.您所做的就是将MaintainScrollPositionOnPostback 属性设置为true.但是,在 MVC 中,我不使用回发,所以这对我不起作用.处理这个问题的标准方法是什么?

Im working on a project in MVC and have enjoyed learning about it. There are a few growing pains but once you figure them out it's not bad. One thing that is really simple in the WebForms world is maintaining the scroll position on a page. All you do is set the MaintainScrollPositionOnPostback property to true. However, in MVC, Im not using postbacks so this will not work for me. What is the standard way of handling this?

Ajax 是可以接受的,但我也想知道如果没有 AJAX,你会怎么做.

Ajax is acceptable, but I was also wondering how you would do it without AJAX.

推荐答案

MaintainScrollPositionOnPostback 的工作方式是它有一对隐藏字段:__SCROLLPOSITIONX 和 __SCROLLPOSITIONY

The way MaintainScrollPositionOnPostback works is that it has a pair of hidden fields: __SCROLLPOSITIONX and __SCROLLPOSITIONY

在回发时,它会设置这些,

On a postback, it sets these,

function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
    return window.pageYOffset;
}
else {
    if (document.documentElement && document.documentElement.scrollTop) {
        return document.documentElement.scrollTop;
    }
    else if (document.body) {
        return document.body.scrollTop;
    }
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
    if (__nonMSDOMBrowser) {
        theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
        theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
    }
    else {
        theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
        theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
    }
    if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
        return this.oldSubmit();
    }
    return true;
    }

然后它调用RestoreScrollPosition:

and then it calls RestoreScrollPosition:

function WebForm_RestoreScrollPosition() {
    if (__nonMSDOMBrowser) {
        window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
    }
    else {
        window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
    }
    if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
        return theForm.oldOnLoad();
    }
    return true;
}

但正如大多数人所说,MVC 无论如何都应该避免回发.

But as most people said, MVC should be avoiding postbacks anyway.

这篇关于如何在 MVC 中保持滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆