滚动到锚点

时间:2015-02-26 19:27:16

标签: javascript jquery html anchor

我试图为我的网站编写一个菜单,可以滚动到同一页面上的锚点和不同页面上的锚点。

第一个是工作。代码是:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

每个页面的菜单都相同,我无法在每个页面上编辑代码。所以HTML代码基本上是:

<a id="mylink" href="http://www.mcsoftware.com.br/sitemc/#allcontentcontact"><span>Contato</span></a>
<a id="mylink2" href="http://www.mcsoftware.com.br/sitemc/#bluecontent"><span>Parceiros</span></a>

我使用javascript来检测用户是否在主页上,如果是,则会更改href行为,因为它只在主页上表示锚点位于同一页面上的菜单。看:

var url = "http://www.mcsoftware.com.br/sitemc/";
$(function(){
  if (location.href==url){
    $('#menu #mylink').attr("href","#allcontentcontact");
    $('#menu #mylink2').attr("href","#bluecontent");
  }
});

现在,问题是我在帖子开头所说的第二部分:滚动到不同页面上的锚点。 那么,我应该使用什么脚本来制作技巧并且不会影响我已经完成的所有事情?可能吗? (并且代码需要隐藏&#34;#nameoftheanchor&#34;来自URL,就像第一个代码已经做的那样)

谢谢!

2 个答案:

答案 0 :(得分:0)

我做了一些非常有效的事情!但是当锚点在另一页面上时,仍会在URL上显示“#anchortag”。

<script>
var url = "http://www.mcsoftware.com.br/sitemc/";
if (location.href==url) {
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
} else {
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();
    }
});
}
</script>

任何帮助?

答案 1 :(得分:0)

要回答第二个问题,可以使用

更改浏览历史记录

window.history.pushState()window.history.replaceState()

有关如何使用每项功能,请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

window.location.pathname将检索当前的网址路径。因此,结合这些概念,我想出了以下内容:

history.pushState("", "", window.location.pathname);

这应该删除哈希,同时保持其余的网址。如果这没有解决您的问题,希望它至少可以让您开始使用正确的路径

相关问题