您的位置:首页技术文章
文章详情页

vue添加锚点,实现滚动页面时锚点添加相应的class操作

浏览:51日期:2023-10-15 10:32:57

第一步,给vue页面添加锚点

.orange{ color: #f97910;}

<template> <div ref='content'> <div class='tabbar'> <div @click.prevent='tabclick(index)' v-for='(item,index) in productTile' :key='index' :class='{orange:index==current}'>{{item}}</div></div> <div id='0'>...</div> <div id='1'>...</div> <div id='2'>...</div> </div><template>

tabclick(index){ this.current=index; let anchorElement = document.getElementById(index); if(anchorElement) { anchorElement.scrollIntoView(); } },

第二步:给class为productDetail的<div>部分加height:100%;overflow-y: scroll;

.productDetail { width: 100%; height: 100%; display: flex; flex-direction: column; overflow-y: scroll;}

第三步,添加监听事件

document.getElementsByClassName(’productDetail’)[0]; vue中同理于:this.$refs.contentmethods:{ handleScroll(el) { this.scrollTop = this.$refs.content.scrollTop; if (this.scrollTop >= 460) { this.current = 2 } else if (this.scrollTop < 460 && this.scrollTop >= 360) { this.current = 1 } else { this.current = 0 } },},mounted() { //scoll滚动事件监听 var pro_detail_page = document.getElementsByClassName(’productDetail’)[0]; pro_detail_page.addEventListener(’scroll’, this.handleScroll);},

注:给最外层div添加height:100%后,mint-ui的轮播图就会展示不出来。我们可以修改mint-ui的默认overflow属性,改为:overflow:visible

补充知识:使用Vuepress自动生成markdown的目录时,一旦标题有数字时便无法跳转的问题解决

问题描述

最近在用vuepress写网页文档的时候发现了一个问题,就是我用markdown书写的标题中如果有类似 1.2 XXX 的标题时,当使用官方文档给出的:

[[toc]]

自动生成目录时,最终生成的网页,含有数字的标题是无法跳转到相应位置的。

问题分析

查看官方开发文档后发现,这跟vuepress的默认配置有关,从如图1所示markdown.slugify函数可以看到,我们需要修改其配置。

markdown.slugify函数

vue添加锚点,实现滚动页面时锚点添加相应的class操作

图1 markdown.slugify函数

点击图中的source,跳转到GitHub的工程页面,可以看到如下的代码段:

// string.js slugify drops non ascii chars so we have to// use a custom implementation here// @ts-ignoreimport { remove as removeDiacritics } from ’diacritics’ // eslint-disable-next-line no-control-regexconst rControl = /[u0000-u001f]/gconst rSpecial = /[s~`!@#$%^&*()-_+=[]{}|;:'’<>,.?/]+/g export = function slugify (str: string): string { return removeDiacritics(str) // Remove control characters .replace(rControl, ’’) // Replace special characters .replace(rSpecial, ’-’) // Remove continous separators .replace(/-{2,}/g, ’-’) // Remove prefixing and trailing separtors .replace(/^-+|-+$/g, ’’) // ensure it doesn’t start with a number (#121) .replace(/^(d)/, ’_$1’) // lowercase .toLowerCase()}

看到了其中有一句ensure it doesn’t start with a number (#121),可以知道这就是问题所在:

// ensure it doesn’t start with a number (#121)

.replace(/^(d)/, ’_$1’)

我们的标题数字被这句代码替换掉了,导致最终的链接根本没有指向标题,故无法跳转。

问题解决

根据GitHub页面上的配置路径,找到自己安装的vuepress模块的配置路径,我的路径是:

D:my_programnodejsnode_globalnode_modulesvuepressnode_modules@vuepressshared-utilslibslugify.js

打开 slugify.js 文件,并将上述的代码段注释掉,问题即可解决。

以上这篇vue添加锚点,实现滚动页面时锚点添加相应的class操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: vue