繁体   English   中英

阻止锚标签href跳转到其页面

[英]Keep anchor tag href from jumping to it's page

我的HTML中有以下锚标记,用于将HTML位置的contents加载到当前页面的content div中。 这个定位标记是我用来生成目录的Bootstrap树视图插件的一部分:

<a href="/Introduction/index.html#1-1-overview1" style="color:inherit;">1.1 Overview</a>

在我的JavaScript中,我有以下代码用于侦听两个事件。 一个用于锚标记,以便禁用默认行为,另一个用于处理锚标记,并加载内容并滚动到锚,如下所示:

    $("a[href*='#']").click(function(e) {
        e.preventDefault();
    });

    // Add smooth scrolling to all links inside a navbar
    $treeview.on('nodeSelected', function (e, data) {
        e.preventDefault();

        if (data && data.href !== "") {
            // Split location and hash
            var hash = data.href.match(/[#].*/g)[0];
            var location = data.href.match(/[^#]*/g)[0];

            if (prevLocation === location) {
                // Don't reload page if already at same location as last clicked
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            } else {
                prevLocation = location;
                $('#contents').load(location, function () {
                    $('html, body').animate({
                        scrollTop: $(hash).offset().top - 55
                    }, 200);
                });
            }

        }
        $body.scrollspy('refresh');
        $sideBar.affix('checkPosition');
    });

我所看到的是,第一次单击我的目录中的节点,它按预期将HTML加载到内容div中,但是第二次单击时,尽管我做了很多努力,但它加载了定位标记中引用的HTML页面跟踪我之前是否像上面的条件逻辑一样加载了它。 我还注意到,在随后的单击中,没有调用锚定选择器。

知道如何才能使TOC最初将HTML从另一个页面加载到当前页面,然后在随后的调用中滚动到定位位置(即章节)吗?

结合这两个函数并返回false似乎可以如下工作:

     $("a[href*='#']").click(function(e) {
        e.preventDefault();

        if (this && this.href !== "") {
            // Split location and hash
            var hash = this.href.match(/[#].*/g)[0];
            var location = this.href.match(/[^#]*/g)[0];

            if (prevLocation === location) {
                // Don't reload page if already at same location as last clicked
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            } else {
                prevLocation = location;
                $('#contents').load(location, function () {
                    $('html, body').animate({
                        scrollTop: $(hash).offset().top - 55
                    }, 200);
                });
            }

        }
        $body.scrollspy('refresh');
        $sideBar.affix('checkPosition');
        return false;
    });

暂无
暂无

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

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