zoukankan      html  css  js  c++  java
  • 文章标题目录锚点功能

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

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

    项目地址在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		
    
    

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

    前进道路长,学习不可怠
  • 相关阅读:
    [51nod1384]全排列
    [51nod1256]乘法逆元
    [51nod1106]质数检测
    [51nod1058]求N!的长度
    2017 world final
    [Manacher+bit]Palindrome
    [hdu3068]最长回文(Manacher算法)
    [trie]字典树模板
    [凸包]Triangles
    LintCode-366.斐波纳契数
  • 原文地址:https://www.cnblogs.com/mrzll/p/10384864.html
Copyright © 2011-2022 走看看