滚动到锚点

问题描述 投票:1回答:1

我有下面的userjs,它的目的是去除URL的锚点部分,但仍然跳转到它。

// ==UserScript==
// @name PurgeAnchor
// @include *
// ==/UserScript==
(function() {
 var reg=/^(.*)\#(.*)$/;
 var match=reg.exec(location);
 function ObjectPosition(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
 }
 if(match) {
    document.location.replace(match[1]);
    sessionStorage.setItem("anchor", match[2]);
 }
 window.addEventListener("load", (function() {
         var anchor=sessionStorage.getItem("anchor");
         if(anchor!==null) {
             var obj=document.anchors.item(anchor);
             // var obj=document.getElementById(anchor);
             // if(obj===null) {
                 // obj=document.getElementsByName(anchor)[0];
             // }
             var pos=0;
             if(obj!==null) {
                 pos=ObjectPosition(obj);
                 window.scrollTo(0, pos);
             }
             sessionStorage.removeItem("anchor");
         }
     }), false);
 })()

问题是,如果我有一个空的 <a> 标签的名称设置,它的跳转失败。obj.scrollIntoView() 也失败了.Opera-10.52_pre6306, Gentoo.

javascript anchor opera userjs
1个回答
0
投票

好吧,花了点时间,但我想我终于明白了。

(function detectSaveAndRedirect() {
            window.addEventListener('load', function() {
                // If the URL already has a hash, remove it.
                if (location.hash.length > 0) {
                    sessionStorage.setItem('anchor',location.hash.substr(1))
                    location.hash = ''
                }
                window.addEventListener('hashchange', function(event) {
                    if (sessionStorage.getItem('anchor')) {
                        event.preventDefault();
                        document.getElementById(sessionStorage.getItem('anchor')).scrollIntoView()
                        sessionStorage.removeItem('anchor')
                    }
                });
                // If links have hashes, remove them.
                document.getElementsByTagName('a').forEach(function(a) {
                    if (
                        (new URL(a.href).host == location.host) &&
                        (a.hash.length > 0)
                    ) {
                        a.addEventListener('click',function(event) {
                            a.removeAttribute('href')
                            a.scrollIntoView();
                        });
                    }
                });
            })
        })()
© www.soinside.com 2019 - 2024. All rights reserved.