繁体   English   中英

ASP.NET导航到后面的代码锚点

[英]ASP.NET navigate to anchor in code behind

我有一个简单的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中不起作用? 我错过了什么吗?

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

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

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

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

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

谢谢你的回答!

门多萨,你可以使用原生的scrollIntoView功能。

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

this.ClientScript.RegisterStartupScript(this.GetType(),
                                        "navigate",
                                        "document.getElementById('id_of_the_element').scrollIntoView();",
                                        true);

我遇到过这一次。 你看过实际的HTML了吗? 如果我记得的话,FireFox对锚点的情况很敏感。 我不知道最近是否改变了。

您可以尝试使用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,但它可能会解决你的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM