diff --git a/src/Cherry.config.js b/src/Cherry.config.js index 2acf4515..d89585ca 100644 --- a/src/Cherry.config.js +++ b/src/Cherry.config.js @@ -249,6 +249,7 @@ const defaultConfig = { autofocus: true, }, writingStyle: 'normal', // 书写风格,normal 普通 | typewriter 打字机 | focus 专注,默认normal + keepDocumentScrollAfterInit: true, // 在初始化后是否保持网页的滚动,true:保持滚动;false:网页自动滚动到cherry初始化的位置 }, toolbars: { theme: 'dark', // light or dark diff --git a/src/Editor.js b/src/Editor.js index fb85c9cb..84bad0e0 100644 --- a/src/Editor.js +++ b/src/Editor.js @@ -371,11 +371,33 @@ export default class Editor { this.refreshWritingStatus(); }; + /** + * 记忆页面的滚动高度,在cherry初始化后恢复到这个高度 + */ + storeDocumentScroll() { + if (!this.options.keepDocumentScrollAfterInit) { + return; + } + this.documentElementScrollTop = document.documentElement.scrollTop; + this.documentElementScrollLeft = document.documentElement.scrollLeft; + } + + /** + * 在cherry初始化后恢复到这个高度 + */ + restoreDocumentScroll() { + if (!this.options.keepDocumentScrollAfterInit) { + return; + } + window.scrollTo(this.documentElementScrollLeft, this.documentElementScrollTop); + } + /** * * @param {*} previewer */ init(previewer) { + this.storeDocumentScroll(); const textArea = this.options.editorDom.querySelector(`#${this.options.id}`); if (!(textArea instanceof HTMLTextAreaElement)) { throw new Error('The specific element is not a textarea.'); @@ -510,6 +532,7 @@ export default class Editor { } // 处理特殊字符,主要将base64等大文本替换成占位符,以提高可读性 this.dealSpecialWords(); + this.restoreDocumentScroll(); } /** diff --git a/types/cherry.d.ts b/types/cherry.d.ts index 6c2d1194..9a85121a 100644 --- a/types/cherry.d.ts +++ b/types/cherry.d.ts @@ -134,6 +134,8 @@ export interface CherryEditorOptions { codemirror?: object; /** 书写风格,normal 普通 | typewriter 打字机 | focus 专注,默认normal */ writingStyle?: string; + /** 在初始化后是否保持网页的滚动,true:保持滚动;false:网页自动滚动到cherry初始化的位置 */ + keepDocumentScrollAfterInit?: boolean; } export type CherryLifecycle = (text: string, html: string) => void; diff --git a/types/editor.d.ts b/types/editor.d.ts index 1b5adebb..d71e88ce 100644 --- a/types/editor.d.ts +++ b/types/editor.d.ts @@ -46,6 +46,7 @@ export type EditorConfiguration = { toolbars: any; value?: string; convertWhenPaste?: boolean; + keepDocumentScrollAfterInit?: boolean; codemirror: CodeMirror.EditorConfiguration; onKeydown: EditorEventCallback; onFocus: EditorEventCallback;