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