使用animate将标签链接锚定到不同页面上的ID

Anchor tag link to ID on different page with animate

本文关键字:ID animate 标签 链接 使用      更新时间:2024-06-11

我有两个页面的网站,我试图将第二个页面链接回div所在的第一个页面。

<li class="menuitem">
    <a href="index.html#services">Go Back</a>
</li>

它转到带有id标记服务的div,并将id标记留在地址栏上。

我正在尝试将它动画化到这个位置,并从地址栏中删除id标记。

这就是第1页的样子-

<div id="home"></div>
<div id="about"></div>
<div id="gallery"></div>
<div id="services"></div>
<div id="contact"></div>

jquery用于链接同一页面中的div-

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

使用window.location.hash可以读取和写入哈希值。因此,在页面加载上,您基本上会执行以下操作:

$("html, body").animate({ 
   scrollTop: $('#'+window.location.hash).offset().top 
}, 1000);
window.location.hash='';

加载后无法修改URL,必须使用请求

http://api.jquery.com/focus/

尝试使用cookie存储,然后使用jquery,您可以专注于这一

或者使用javscript

window.onload=getloaded();
function getloaded() {    
      var g=document.URL ;
      if(g.indexOf('services')!=-1) {
          // focus on services
      }
}

或者像这个

$('html,body').animate({scrollTop:$("#your element").offset().top},'slow');

只需将锚点标签与一起使用

href="my_page.html#my_anchor_name"

其将滚动到页面CCD_ 3中id等于CCD_。如果要在同一页面内进行链接,只需省略页面名称my_page.html即可。