【问题标题】:Anchor link for same and different page相同和不同页面的锚链接
【发布时间】:2015-02-26 05:49:45
【问题描述】:

我正在使用该代码:

$(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;
      }
    }
  });
});

<a href="#allcontentcontact"> 链接到div <div id="allcontentcontact"></div>

问题是: “#allcontentcontact”在我的主页上,所以代码只有在我在主页上时才能完美运行。但我有一个固定的菜单链接到其他页面!因此,当我在另一个页面上时,我需要一些东西来使我的 a href 链接到该 div。

谢谢!

【问题讨论】:

  • html代码在哪里?
  • 我想我发布了所有重要的信息。你还需要看什么?

标签: javascript jquery html anchor


【解决方案1】:

感谢您的回答,我做到了! :)

<script>
var url = "http://192.168.1.157/wp/";
$(function(){
  if (location.href==url){
    $('#menu #mylink').attr("href","#bluecontent");
    $('#menu #mylink2').attr("href","#allcontentcontact");
  }
});
</script>

URL 很奇怪,因为我在 localhost 上编码,但代码运行良好。 :)

还有 HTML

<a id="mylink" href="<?php bloginfo('url'); ?>#bluecontent"><span>Parceiros</span></a>

<a id="mylink2" href="<?php bloginfo('url'); ?>#allcontentcontact"><span>Contato</span></a>

几乎完成了。所有的链接都能完美地把我带到他们指定的锚点。

问题是:我在其他页面上滑动到锚点的脚本包括 URL 上的 #bluecontent 和 #allcontentcontact。是否可以从 URL 中删除它? 代码如下:

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();
    }
});

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 2020-04-29
    • 1970-01-01
    • 2022-11-26
    • 2015-03-29
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多