文章標題目錄錨點功能


想必大家開發網站,可能會用到一些文章或者一段長篇幅的介紹,那么方便用戶閱讀與定位,這個功能就十分方便啦

最近剛開發的新站中,對於軟件的介紹內容,需要做標題的提取與錨點定位,就如下圖效果所示:

項目地址在www.macw.com 軟件內容展示頁面中

這個時候,對於后台動態生成的內容,我們如何去提取標題並且生成目錄呢,又如何去確定標題所在文檔的高度,並且在圖片加載完成后不影響高度的定位?

從思路上,我們首先考慮到如何去使用 后面我們所要寫的函數,我們需要提供一些什么?

我們需要提供動態生成文章的容器,與生成標題的標簽,例如特定的 .title類名,或者h2, h3等標簽。

然后,將兩個元素作為參數傳入我們的函數中,在函數中我們去做一系列的處理

根據標題標簽獲取所有標簽,
並等待所有圖片加載后獲取標簽所在高度放到一個數組中,
創建側邊目錄導航加入頁面,添加點擊功能與錨點定位

下面展示代碼


;(function(win, $){
    class ContentFixNav {
        constructor(wrap, title) {
            this.wrapDoms = wrap;
            this.titleDoms = title;
            this.init();
        }

        init() {
            this.hHeightArr = [];  //初始化數組容器存放 錨點高度
            this.render();  // 渲染功能
        }

        render() {
            $('body').append($('<div id="content-nav"></div>'));  // 生成側邊目錄存放的容器 加入頁面中
            this.contentNav = $('#content-nav');  // 聲明容器

            let _this = this;

            this.titleDoms.each(function(index, el) {
                let textArr = $(this).text().trim().replace(/\s+/g, ' ').split(' '),
                    _text = textArr[textArr.length-1],
                    newText = _text.replace(/\s|\w|:|\(|\)/g, '');  // 做一些標題提取后文案處理,以標題的空格分割,提取最后一組文案,把一些不需要的符號去除

                newText.length < 4? newText = _text.replace(/\s|:|\(|\)/g, ''): newText = newText.substr(newText.length - 4); //  如果剩余文案字符不足4個字符,刪除符號,足夠就取最后四個

                let $span = $('<span>').text(newText);  // 生成目錄 放入容器

                _this.contentNav.append($span);

            });

            this.getHeightArr(); // 調用獲取高度
        }

        getHeightArr() {
            let imgs = this.wrapDoms.find('img'),  // 獲取整個文章容器中圖片
                len = imgs.length,
                promiseAll = [],
                _this = this;

            for(let i = 0 ; i < len ; i++){  // 遍歷 生成promise對象加入到數組中
                promiseAll[i] = new Promise((resolve, reject)=>{
                    if(imgs[i].complete) {  // 這里判斷圖片已經完成的 改變狀態為成功
                        resolve(imgs[i])
                    }else {
                        imgs[i].onload = function(){ // 否則等圖片加載后 改變狀態為成功
                            resolve(imgs[i])
                        }
                    }
                    
                })
            };
            
            Promise.all(promiseAll).then((img)=>{  // Promise.all方法用於將多個 Promise 實例,包裝成一個新的 Promise 實例, 等到所有promise都狀態為成功后 進入 .then 回調
                _this.titleDoms.each(function(index, el) {  // 遍歷標題 獲取高度加入到錨點數組中
                    _this.hHeightArr.push(Math.ceil($(el).offset().top));
                })
                _this.contentNav.show(); // 顯示錨點目錄
                _this.initEvent(); // 初始事件
            })

        }

        initEvent() {
            this.contentNav.on('click', 'span', this.scrollToHeight.bind(this));  // 初始點擊定位功能

            $(window).on('scroll', this.watchScroll.bind(this));  // 初始滾動監聽 
        }

        scrollToHeight(e) {
            let _index = $(e.target).index(),
                _this = this;

            $('body, html').animate({ scrollTop: _this.hHeightArr[_index] }, 300);  // 滾動到指定位置
        }

        watchScroll(e) {
            let navs = this.contentNav.children('span'), 
                scrollTop = $(e.target).scrollTop(),
                _index,
                _this = this;
            // 遍歷錨點高度數組, 根據區間 確當當前位置索引,添加選擇狀態
            for (let i = 0; i < _this.hHeightArr.length; i++) { 
                let height_0 = _this.hHeightArr[0],
                    height_1 = _this.hHeightArr[i],
                    height_2 = _this.hHeightArr[i+1];
                if(height_0 > scrollTop) {
                    _index = -1;
                    break;
                } else if(!height_2 || (height_1 <= scrollTop && height_2 > scrollTop)) {
                    _index = i;
                    break;
                }    
            }

            _index >= 0 ? __commonToggleActive(navs.eq(_index)): navs.removeClass('active'); // __commonToggleActive 前面我有寫道的公共方法,切換當前狀態類
        }
    }

    win.ContentFixNav = ContentFixNav;
})(window, $);


// 在其他地方調用

let wrap = '', h3 = '';

new ContentFixNav(wrap, h3);

我的樣式文件里面,容器與目錄是這樣的


#content-nav 
	width auto 
	padding-left 15px
	position fixed 
	left 50%
	margin-left -680px 
	top 60%
	z-index 999
	display none
	span 
		display block
		font-size 12px 
		cursor pointer
		white-space nowrap
		height 30px
		line-height 30px 
		position relative
		color #999
		&.active 
			color #1398ff
			&:before 
				background-color #1398ff
		&:before 
			content ""
			position absolute
			left -12px 
			top 13px 
			width 5px 
			height 5px 
			border-radius 50%
			background-color #bbb		

這樣就可以實現文章目錄提取與錨點定位啦~ 感謝觀看


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM