【问题标题】:Programmatically scroll to an Anchor Tag以编程方式滚动到锚标记
【发布时间】:2010-09-20 21:57:35
【问题描述】:

考虑以下代码:

<a href="#label2">GoTo Label2</a>
... [content here] ...
<a name="label0"></a>More content
<a name="label1"></a>More content
<a name="label2"></a>More content
<a name="label3"></a>More content
<a name="label4"></a>More content

有没有办法模拟点击“GoTo Label2”链接通过代码滚动到页面上的相应区域?

编辑:可接受的替代方法是滚动到具有唯一 ID 的元素,该元素已存在于我的页面上。如果这是一个可行的解决方案,我会添加锚标签。

【问题讨论】:

标签: asp.net navigation anchor


【解决方案1】:

如果你还在元素上加上一个 ID,这个 JS 通常对我来说效果很好:

document.getElementById('MyID').scrollIntoView(true);

这很好,因为它还可以定位可滚动的 div 等,以便内容可见。

【讨论】:

    【解决方案2】:

    使用javascript:

    window.location.href = '#label2';
    

    如果您需要从后面的服务器/代码执行此操作,您只需发出此 Javascript 并将其注册为该页面的启动脚本。

    【讨论】:

    • 这对我来说效果很好,仍然可以使用锚。嵌入在 winforms 应用程序中的 Webbrower 控件。
    【解决方案3】:

    从服务器端移动到锚点,例如 c#。

    ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#form';", true);
    

    【讨论】:

      【解决方案4】:

      我想这会起作用:

      window.location="<yourCurrentUri>#label2";
      

      【讨论】:

        【解决方案5】:

        解决办法

        document.getElementById('MyID').scrollIntoView(true);
        

        几乎在所有浏览器中都能正常工作,而我注意到在某些浏览器或某些移动设备(例如某些黑莓版本)中无法识别“scrollIntoView”功能,因此我会考虑此解决方案(比上一个):

        window.location.href = window.location.protocol + "//" + window.location.host + 
                               window.location.pathname + window.location.search + 
                               "#MyAnchor";
        

        【讨论】:

          【解决方案6】:

          如果元素是锚标签,你应该可以这样做:

          document.getElementsByName('label2')[0].focus();
          

          【讨论】:

          【解决方案7】:

          使用 window.location.hash 时没有“#”

          【讨论】:

            【解决方案8】:

            您可以只打开附加名称的新 URL,例如 http://www.example.com/mypage.htm#label2

            在 JavaScript 中,

            location.href = location.href + '#label2';
            

            【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-16
            • 2011-01-15
            • 2010-11-13
            • 2014-05-22
            相关资源
            最近更新 更多