在我的 MVC 4 Web 应用程序中,其中一个 View 是列出房屋对象,并且在每个对象的右侧,用户都可以更改语言。假设您正在页面中间阅读有关某个对象的内容,并决定要更改语言。然后加载一个新页面,看起来完全相同,但现在使用另一种语言的文本。问题是新页面从头开始(当然因为它是新页面),并且我希望新加载的页面具有与前一个页面相同的滚动位置。
要更好地了解,您可以访问该网站:http://www.lomahovi.com然后点击住宿。在那里您将看到每个对象的链接,您可以在其中在英语和俄语之间切换。
因此,如果客户正在查看英语对象,并决定他/她想要切换到俄语,我不希望页面从头开始,而是应该位于与英语相同的对象/位置上它是英文的,因此客户无需向下滚动页面即可再次找到该对象。
感谢任何帮助。 谢谢,
彼得
最佳答案
您可以将当前屏幕位置发送回更改语言的 Controller - 像这样--> Link
将结果存储到临时对象中(即 TempData ["scrollTo"])。
在您的 View 中,检查 TempData["scrollTo"] 是否不为空,如果不为空,则导航到该位置(使用 jquery)
编辑:
类似这样的事情:
在 View 上:(将其与您的语言点击绑定(bind))
var screenTopPosition = $(document).scrollTop(); //--Send this var to your controller as url param or w/e you prefer
在 Controller 上
TempData["scrollTo"] = position; //where position is the param you received from the view
再次查看 View :(使用 Razor)
$(function(){ @if (TempData["scrollTo"]!=null) { var screenTop = @TempData["scrollTo"]; $('#content').css('top', screenTop); //replace #content with your main div } });
添加:
要使用 Html Helper 发送 java 脚本变量,您需要这样的东西( View ):
<div style="height:1000px">
test
</div>
<div style="height:1000px">
<a id="link" href="#">
Click me
</a>
</div>
@section scripts{
<script>
var link = '@Url.Action("ActionName", "ControllerName", new { screenPosition = 123 })'
$(function () {
$("#link").click(RedirectWithScreenPos);
});
function RedirectWithScreenPos() {
var screenPos = $(document).scrollTop();
link = link.replace('123', screenPos);
window.location.href = link;
}
</script>
}
关于javascript - 加载新页面时如何在 MVC 4 中设置滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30015186/