当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vuepress锚点hash滚动问题

vuepress锚点hash滚动问题

2020年07月17日  | 移动技术网IT编程  | 我要评论
vuepress锚点hash跳动问题问题描述vuepress建立网站的某个URL如果带有锚点,如http://test/test-hash.html#hasherror,刷新该URL,并不能滑动到相应的hasherror锚点,或者打开新的带有锚点的链接不能跳到相应的地方。研究调查在vuepress的github issue中找到相关的问题——Initial load does not scroll to the heading referenced by the document hash

vuepress锚点hash滚动scroll问题

问题描述

vuepress建立网站的某个URL如果带有锚点,如http://test/test-hash.html#hasherror,刷新该URL,并不能滑动到相应的hasherror锚点,或者打开新的带有锚点的链接不能跳到相应的地方。

研究调查

  1. 在vuepress的github issue中找到相关的问题——Initial load does not scroll to the heading referenced by the document hash

  2. 又在1的问题下发现关于中文hash需要解码(decodeURIComponent)的提示——中文在URL中会被转码,需要使用decodeURIComponent方法解码

解决方案

根据以上调查以及实践,解决方案如下:


在.vuepress文件夹下添加enhanceApp.js文件

export default ({ router }) => {
	if(typeof process === 'undefined' || process.env.VUE_ENV !== 'server') {
		router.onReady(() => {
			const { app } = router;

			app.$once("hook:mounted", () => {
				setTimeout(() => {
					const { hash } = document.location;
                    if (hash.length > 1) {
            		const id = decodeURIComponent(hash.substring(1));
            		const element = document.getElementById(id);
            		if (element) element.scrollIntoView();
          }
				}, 500);
			});	
		});
	}
}

注意:如果hash有中文,要加decodeURIComponent

本文地址:https://blog.csdn.net/sendudu/article/details/107368962

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网