Skip to content

Commit

Permalink
feat: #653 增加新的配置开关,打开后cherry完成初始化后会根据hash进行 滚动定位
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsonliu committed Nov 21, 2023
1 parent b573fd3 commit 50bc19d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Cherry.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
24 changes: 24 additions & 0 deletions src/Cherry.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}

/**
Expand Down
2 changes: 2 additions & 0 deletions types/cherry.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export interface CherryOptions {
autoScrollByCursor: boolean;
/** 外层容器不存在时,是否强制输出到body上 */
forceAppend: boolean;
/** cherry初始化后是否检查 location.hash 尝试滚动到对应位置 */
autoScrollByHashAfterInit: boolean;
/** 挂载DOM节点ID,引擎模式下不生效 */
id?: string;
/** 挂载DOM节点,引擎模式下不生效 */
Expand Down

0 comments on commit 50bc19d

Please sign in to comment.