簡體   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