From 50bc19d6ed73e644a0f610face5eb644220dacd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?sunsonliu=28=E5=88=98=E9=98=B3=29?= Date: Tue, 21 Nov 2023 17:27:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20#653=20=E5=A2=9E=E5=8A=A0=E6=96=B0?= =?UTF-8?q?=E7=9A=84=E9=85=8D=E7=BD=AE=E5=BC=80=E5=85=B3=EF=BC=8C=E6=89=93?= =?UTF-8?q?=E5=BC=80=E5=90=8Echerry=E5=AE=8C=E6=88=90=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E5=90=8E=E4=BC=9A=E6=A0=B9=E6=8D=AEhash=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=20=E6=BB=9A=E5=8A=A8=E5=AE=9A=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Cherry.config.js | 2 ++ src/Cherry.js | 24 ++++++++++++++++++++++++ types/cherry.d.ts | 2 ++ 3 files changed, 28 insertions(+) diff --git a/src/Cherry.config.js b/src/Cherry.config.js index b8dfe4e9..2acf4515 100644 --- a/src/Cherry.config.js +++ b/src/Cherry.config.js @@ -390,6 +390,8 @@ const defaultConfig = { forceAppend: true, // The locale Cherry is going to use. Locales live in /src/locales/ locale: 'zh_CN', + // cherry初始化后是否检查 location.hash 尝试滚动到对应位置 + autoScrollByHashAfterInit: false, }; export default cloneDeep(defaultConfig); diff --git a/src/Cherry.js b/src/Cherry.js index f7ca457d..2a16976b 100644 --- a/src/Cherry.js +++ b/src/Cherry.js @@ -186,6 +186,30 @@ export default class Cherry extends CherryStatic { // 切换模式,有纯预览模式、纯编辑模式、双栏编辑模式 this.switchModel(this.options.editor.defaultModel); + + // 如果配置了初始化后根据hash自动滚动 + if (this.options.autoScrollByHashAfterInit) { + setTimeout(this.scrollByHash.bind(this)); + } + } + + /** + * 滚动到hash位置,实际上就是通过修改location.hash来触发hashChange事件,剩下的就交给浏览器了 + */ + scrollByHash() { + if (location.hash) { + try { + const { hash } = location; + // 检查是否有对应id的元素 + const testDom = document.getElementById(hash.replace('#', '')); + if (testDom && this.previewer.getDomContainer().contains(testDom)) { + location.hash = ''; + location.hash = hash; + } + } catch (error) { + // empty + } + } } /** diff --git a/types/cherry.d.ts b/types/cherry.d.ts index def5755e..6c2d1194 100644 --- a/types/cherry.d.ts +++ b/types/cherry.d.ts @@ -48,6 +48,8 @@ export interface CherryOptions { autoScrollByCursor: boolean; /** 外层容器不存在时,是否强制输出到body上 */ forceAppend: boolean; + /** cherry初始化后是否检查 location.hash 尝试滚动到对应位置 */ + autoScrollByHashAfterInit: boolean; /** 挂载DOM节点ID,引擎模式下不生效 */ id?: string; /** 挂载DOM节点,引擎模式下不生效 */