锚点滑动jq 关于HTML锚点定位几个不同场景的解决方案

  
  
// Load jQuery.js firstly
jQuery ( function () {
     jQuery ( 'a[href*=#]' ). click ( function () {
         if ( location . pathname . replace ( /^\// , '' ) == this . pathname . replace ( /^\// , '' ) && location . hostname == this . hostname ) {
             var $target = jQuery ( this . hash );
             var $url = this . hash . slice ( 1 );
             var $scrollTime = 500 ;
             function updateUrl () {
                 window . location . hash = encodeURIComponent ( $url );
             }
             $target = $target . length && $target || jQuery ( '[name=' + $url + ']' );
             if ( ! $url ) {
                 return false ;
             } else if ( $target . length ) {
                 var targetOffset = $target . offset (). top ;
                 jQuery ( 'html,body' ). animate ({
                     scrollTop : targetOffset
                 }, $scrollTime );
                 setTimeout ( updateUrl , $scrollTime + 100 )
                 return false ;
             }
         }
     });
}); 情形1: 目标页面有个 `position:fixed;height:50px;` 的顶部导航栏,这部分会遮住文章正文内容,正文中的所有`#part-1` 这样的锚点都会有50px的误差,解法很简单,如下:
jQuery('html,body').animate({
    scrollTop: targetOffset - 50
}, $scrollTime);

如果要兼容从别的页面锚过来,可以再加个触发器监控`location.hash`:

$('body').append('<a id="anchor-temp" href="' + location.hash + '"></a>');
window.setTimeout(function() {
    $('#anchor-temp').trigger('click');
}, 2000);

情形2:
需要强行根据URL中的锚标记进行页面跳转,如:
http://aaa.bbb/ccc#part-1 -> http://aaa.bbb.ccc/1/ 这样我们首先会想到使用`.htaccess` 进行重定向,可实践后发现不可行,原因见:stackoverflow

# RewriteRule /ccc/(\d+)(.*) http://aaa.bbb/ccc/$1 [NE]
RewriteRule /ccc/(\d+).#.(.*) http://aaa.bbb/ccc/$1 [NE]

于是退而求其次,用下面的js完成:

if(window.location.hash.split('-')[0] == '#part')
window.location.href = window.location.href.split('#')[0];

情形3:
锚点和URL的字符串统一关系以及平滑滑动的动画需求,可以看下这段小script的demo:
https://github.com/hzlzh/Anchor-Scroll

版权所有© HzlzH | 本文采用 BY-NC-SA 进行授权
转载需注明 转自: 《 关于HTML锚点定位几个不同场景的解决方案

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值