1

也许这对于 ASP.NET MVC 是不可能的,因为我找不到答案。我想要做的是单击一个链接,该链接将加载目标页面,然后滚动到该页面上的锚点。在这个问题中回答了一个完美的例子。

但是,我如何让它与 JavaScript/jQuery 一起使用?

更新:使用此代码,除了 setTimeOut 定义外,一切正常。它只是继续运行脚本,直到我单击停止,然后如果向下滚动到锚点。这是为什么?

var jump = function (e) {
    if (e) {
        e.preventDefault();
        var target = $(this).attr("href");
    } else {
        var target = location.hash;
    }

    $('html,body').animate(
{
   scrollTop: $(target).offset().top
}, 2000, function () {
   location.hash = target;
});

}

$('html, body').hide();
$(document).ready(function () {
    $('a[href^=#]').bind("click", jump);

    if (location.hash) {
        setTimeout(function () {
            $('html, body').scrollTop(0).show();
            jump();
        }, 0);
    } else {
        $('html, body').show();
    }        

});
4

4 回答 4

2

我对asp.net一无所知,但这就是我认为正在发生的事情:

如果在位置提供哈希,ASP.NET MVC 的 MicrosoftAjax 模块会在初始化时重新加载页面。

MVC 框架,即它的 MicrosoftAjax 组件,尝试管理某些浏览器的历史记录,并为此使用 URL 的散列部分,到目前为止,这是一个有效的标准过程。在初始化时,Sys$_Application$initialize()通过_navigate()应用_raiseNavigate()程序方法。而这个专门为 Firefox 做了一些舞蹈:

// Name:        MicrosoftAjax.debug.js
// Assembly:    System.Web.Extensions
// Version:     4.0.0.0
// FileVersion: 4.0.20526.0

if ((Sys.Browser.agent === Sys.Browser.Firefox) && window.location.hash &&
    (!window.frameElement || window.top.location.hash)) {
    window.history.go(0);
}

三个条件:

  1. 浏览器是火狐
  2. 地址在 URL 之后带有一个哈希部分
  3. 它不在框架内

所有这些都在你的情况下通过,野兽被释放:

window.history.go(0);

That instructs browser's history manager to go back or forward by the distance given as argument. -2 goes one step back, 1 goes one step forward. Thus 0 effectively reloads the page. And does it on every page load for any hash given to the page. Can't think of any valid purpose of this line there anyway...

Sure enough if I comment out those rather hairy and pointless lines, it works! It seems to be a backward compatibility attempt for Firefox 3.5 or lower, so I would say remove it or better update your MVC.

于 2012-04-12T15:02:14.647 回答
1

这不是 jQuery 的问题。在你看来,你应该放一些代码,

<script>
  $(function () }

     var hash = window.location.hash;
     var achor = hash.substring(hash.indexOf('#'));

     $('html,body').animate({scrollTop: $("#"+achor).offset().top} 

  });
</script>
于 2012-04-10T18:54:56.527 回答
0

这实际上与 ASP.NET MVC 无关,更多的是关于客户端脚本 (Javascript)。请参阅有关哈希(#)的这个SO线程,因为它与路由相关......我认为这是与ASP.Net MVC相关的唯一项目......

于 2012-04-10T14:38:22.703 回答
0

我部分回答了我自己的问题。我一直使用 Firefox,所以我的测试是在 Firefox 11.0 中进行的。我在 IE 中快速检查了它,它工作正常。在以前版本的 Firefox 中对其进行了测试,并且可以正常工作。它只是在 Firefox 11.0 中不起作用。我将关闭此问题并打开一个新问题来解决适当的问题。

于 2012-04-11T18:20:37.013 回答