欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

文章标题目录锚点功能

程序员文章站 2023-11-03 09:32:28
想必大家开发网站,可能会用到一些文章或者一段长篇幅的介绍,那么方便用户阅读与定位,这个功能就十分方便啦 最近刚开发的新站中,对于软件的介绍内容,需要做标题的提取与锚点定位,就如下图效果所示: 这个时候,对于后台动态生成的内容,我们如何去提取标题并且生成目录呢,又如何去确定标题所在文档的高度,并且在图 ......

想必大家开发网站,可能会用到一些文章或者一段长篇幅的介绍,那么方便用户阅读与定位,这个功能就十分方便啦

最近刚开发的新站中,对于软件的介绍内容,需要做标题的提取与锚点定位,就如下图效果所示:

文章标题目录锚点功能

这个时候,对于后台动态生成的内容,我们如何去提取标题并且生成目录呢,又如何去确定标题所在文档的高度,并且在图片加载完成后不影响高度的定位?

从思路上,我们首先考虑到如何去使用 后面我们所要写的函数,我们需要提供一些什么?

我们需要提供动态生成文章的容器,与生成标题的标签,例如特定的 .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       

这样就可以实现文章目录提取与锚点定位啦~ 感谢观看