Skip to content

Commit

Permalink
feat: #642 在调用setMarkdown/setValue时保持页面的滚动位置
Browse files Browse the repository at this point in the history
  • Loading branch information
sunsonliu committed Dec 7, 2023
1 parent b58de6d commit 5106859
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/Cherry.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ export default class Cherry extends CherryStatic {
* @param {boolean} keepCursor 是否保持光标位置
*/
setValue(content, keepCursor = false) {
this.editor.storeDocumentScroll();
if (keepCursor === false) {
return this.editor.editor.setValue(content);
}
Expand Down Expand Up @@ -607,6 +608,7 @@ export default class Cherry extends CherryStatic {
}
// 强制每次编辑(包括undo、redo)编辑器都会自动滚动到光标位置
codemirror.scrollIntoView(null);
this.editor.restoreDocumentScroll();
}, 50);
} catch (e) {
throw new NestedError(e);
Expand Down
4 changes: 3 additions & 1 deletion src/Editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,7 @@ export default class Editor {
if (!this.options.keepDocumentScrollAfterInit) {
return;
}
this.needRestoreDocumentScroll = true;
this.documentElementScrollTop = document.documentElement.scrollTop;
this.documentElementScrollLeft = document.documentElement.scrollLeft;
}
Expand All @@ -386,9 +387,10 @@ export default class Editor {
* 在cherry初始化后恢复到这个高度
*/
restoreDocumentScroll() {
if (!this.options.keepDocumentScrollAfterInit) {
if (!this.options.keepDocumentScrollAfterInit || !this.needRestoreDocumentScroll) {
return;
}
this.needRestoreDocumentScroll = false;
window.scrollTo(this.documentElementScrollLeft, this.documentElementScrollTop);
}

Expand Down

0 comments on commit 5106859

Please sign in to comment.