简体   繁体   English

相同和不同页面的锚点链接

[英]Anchor link for same and different page

I'm using that code: 我正在使用该代码:

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

and <a href="#allcontentcontact"> to link to the div <div id="allcontentcontact"></div> . <a href="#allcontentcontact">链接到div <div id="allcontentcontact"></div>

The problem is: "#allcontentcontact" is on my homepage, so the code works perfectly only when I'm on the homepage. 问题是:“#allcontentcontact”在我的主页上,所以只有当我在主页上时,代码才能完美运行。 But I have a fixed menu that links to other pages! 但是我有一个固定的菜单链接到其他页面! So I need something that makes my a href links to that div when I'm on another page. 因此,当我在另一个页面上时,我需要一些能够使我的href链接到该div的东西。

Thanks! 谢谢!

Thanks for the answers, I did it! 谢谢你的答案,我做到了! :) :)

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

The URL is strange because I'm coding on localhost, but the code works perfectly. URL很奇怪,因为我在localhost上编码,但代码运行完美。 :) :)

And the HTML 和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>

It's almost done. 它差不多完成了。 All the links works perfectly taking me smoothly to their specified anchors. 所有链接都能很好地完美地带我到他们指定的锚点。

The problem is: my script that slides to anchors on other pages include the #bluecontent and #allcontentcontact on the URL. 问题是:我的脚本滑动到其他页面上的锚点,包括URL上的#bluecontent和#allcontentcontact。 Is it possible to delete that from the URL? 是否可以从URL中删除它? Here is the code: 这是代码:

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

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

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