3

我有一个简单的 Web 表单,代码如下:

//...
//tons of text
//...
<a name="message" />
//...
//tons of text
//...
<asp:Button ID="ButtonSend" 
                runat="server" 
                text="Send"
                onclick="ButtonSend_Click" />

POST 之后,我想将用户导航到我的锚点“消息”。我有以下代码:

protected void ButtonSend_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
                                        "navigate",
                                        "window.location.hash='#message';",
                                        true);
}

这个简单的 JavaScript 在 Firefox 3.5.2 中不起作用 - 浏览器中的 url 正在更改,但页面未导航到锚点。在 IE 8 中它可以完美运行。

为什么这段 JavaScript 代码在 Firefox 中不起作用?我错过了什么吗?

4

4 回答 4

7

我已经解决了我的问题。JavaScript 代码在我的锚点存在之前就被调用了。这就是为什么 Firefox 没有向下滚动页面的原因。

我的代码现在看起来像 tihs:

this.ClientScript.RegisterStartupScript(this.GetType(),
                                        "navigate",
                                        "window.onload = function() {window.location.hash='#message';}",
                                         true);

页面加载后,我正在调用我的简单 JavaScript 函数。

找到解决方案的关键是克莱顿的回答。Firebug 报告 getElementById 正在返回空引用。然后我查看了生成的 HTML,如 andrewWinn 建议的 - 在锚点存在之前调用了 JavaScript。做了一点谷歌搜索并找到了解决方案。

感谢您的回答!

于 2009-08-20T19:07:26.997 回答
5

Mendoza,您可以使用本机scrollIntoView功能。

做你想做的事,只需要写:

this.ClientScript.RegisterStartupScript(this.GetType(),
                                        "navigate",
                                        "document.getElementById('id_of_the_element').scrollIntoView();",
                                        true);
于 2009-08-20T17:31:20.717 回答
1

我遇到过一次。你看过实际的 HTML 吗?如果我记得的话,FireFox 在锚点上是区分大小写的。不知道最近有没有变。

于 2009-08-20T18:13:20.350 回答
0

您可以尝试使用jQuery LocalScroll 插件。使用它,您可以使用以下方式滚动:

$(function() {
    $.scrollTo("#message");
});

或者使用您的 ASP.NET 代码:

protected void ButtonSend_Click(object sender, EventArgs e)
{
    this.ClientScript.RegisterStartupScript(this.GetType(),
                                            "navigate",
                                            "$(function() { $.scrollTo('#message'); });",
                                             true);
}

这不是一个理想的解决方案,特别是如果您还没有在项目中的任何地方使用 jQuery,但它可能会解决您的问题。

于 2009-08-20T18:22:07.417 回答