Skip to content

Commit a879b5b

Browse files
committed
Fixed scrollSpy might not set properly on updateView or windowResize
1 parent 4725415 commit a879b5b

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

public/js/index.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,8 @@ function windowResizeInner() {
470470
clearMap();
471471
syncScrollToView();
472472
editor.setOption('viewportMargin', viewportMargin);
473-
}, windowResizeDelay);
473+
updateScrollspy();
474+
}, 100);
474475
}
475476
}
476477

@@ -803,6 +804,32 @@ function generateScrollspy() {
803804
ui.area.view.scroll();
804805
}
805806

807+
function updateScrollspy() {
808+
var headers = ui.area.markdown.find('h1, h2, h3').toArray();
809+
var headerMap = [];
810+
for (var i = 0; i < headers.length; i++) {
811+
headerMap.push($(headers[i]).offset().top - parseInt($(headers[i]).css('margin-top')));
812+
}
813+
applyScrollspyActive($(window).scrollTop(), headerMap, headers,
814+
$('.scrollspy-body'), 0);
815+
var offset = ui.area.view.scrollTop() - ui.area.view.offset().top;
816+
applyScrollspyActive(ui.area.view.scrollTop(), headerMap, headers,
817+
$('.scrollspy-view'), offset - 10);
818+
}
819+
820+
function applyScrollspyActive(top, headerMap, headers, target, offset) {
821+
var index = 0;
822+
for(var i = headerMap.length - 1; i >= 0; i--) {
823+
if(top >= (headerMap[i] + offset) && headerMap[i + 1] && top < (headerMap[i + 1] + offset)) {
824+
index = i;
825+
break;
826+
}
827+
}
828+
var header = $(headers[index]);
829+
var active = target.find('a[href="#' + header.attr('id') + '"]');
830+
active.closest('li').addClass('active').parent().closest('li').addClass('active').parent().closest('li').addClass('active');
831+
}
832+
806833
//fix for wrong autofocus
807834
$('#clipboardModal').on('shown.bs.modal', function () {
808835
$('#clipboardModal').blur();
@@ -1736,6 +1763,7 @@ function updateViewInner() {
17361763
generateToc('toc');
17371764
generateToc('toc-affix');
17381765
generateScrollspy();
1766+
updateScrollspy();
17391767
smoothHashScroll();
17401768
isDirty = false;
17411769
clearMap();

0 commit comments

Comments
 (0)