【问题标题】:Set page scroll position on page load of MVC view with javascript使用javascript在MVC视图的页面加载上设置页面滚动位置
【发布时间】:2018-04-26 14:06:46
【问题描述】:

我一直在尝试在页面加载时自动转到网页底部。在get AND post上,其实无论view怎么调用,都要自动到页面底部。

我想用 javascript 来做。

看起来很简单,我可以在这里轻松找到。好吧,看起来像这样:

Set page scroll position on page load of MVC app

只有一个问题...答案没有将 javascript 解决方案置于上下文中。而且没有上下文...我不知道将这些行放在哪里,无论我尝试什么...

我不会玩一整天才知道如何做到这一点,所以这里有一个上下文:

@model WhateverModelYouWant
@{
    ViewBag.Title = "Formulaire de reprise";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }

<script type="text/javascript">
    document.getElementById("ImportantStuff").scrollIntoView();
</script>

<h2> TITLE OF THE VIEW <h2>

<div> Lots of content here </div>

<div> Even more content here </div>

<div id="ImportantStuff"> Important stuff here </div>

<input type="submit" value="ImportantButton" >

不用说这不会使页面滚动到任何地方...提前致谢。

错误:

【问题讨论】:

    标签: javascript html asp.net-mvc


    【解决方案1】:

    在您的示例中,无论如何都无法滚动任何内容,因为所有内容都在可见区域中。除此之外,mituw16 已经为您提供了正确的解决方案。这是一个如何使用scrollIntoView函数的示例。

    <script type="text/javascript">
            function scrollToImportantStuff() {
                document.getElementById('ImportantStuff').scrollIntoView()
            }
            window.onload = scrollToImportantStuff;
    </script>
        
        <h2> TITLE OF THE VIEW <h2>
    
        <input type="button" onclick="document.getElementById('ImportantStuff').scrollIntoView()" value="Scroll ImportantStuff into View" />
    
        <div style="height:500px;"> Lots of content here </div>
    
        <div style="height:500px;"> Even more content here </div>
    
        <div id="ImportantStuff"> Important stuff here </div>

    【讨论】:

      【解决方案2】:

      这与 MVC 没有任何关系。它是用javascript完成的。

      document.getElementById("ImportantStuff").scrollIntoView();
      

      https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView

      【讨论】:

      • 谢谢...但这是另一个没有上下文的答案。看我的编辑,我想这就是你想让我做的。而且它也不滚动...
      • 它没有上下文,因为您要求做的事情非常简单。我不认为它需要更多的“上下文”......
      • 很抱歉,您采取这种方式......我们的目标是不让任何人感到沮丧。这对你来说可能看起来太简单了......
      猜你喜欢
      • 1970-01-01
      • 2015-07-12
      • 2015-06-11
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多