Anchor margin-note connectors to the line's text center

This commit is contained in:
2026-11-15 18:10:58 +08:00
parent 91aee141d0
commit a8e7a9f9b9
2 changed files with 25 additions and 49 deletions
+22 -48
View File
@@ -24,66 +24,40 @@
}
// 取注释所在「行」的垂直中点。
// 做法:用 Range 从段落开头量到 .post-note-anchor(零尺寸基准点,贴在行基线上),
// 它的最后一个 rect 就是标记所在那一行的文字片段,取其中点即可。
// 这样既不受上标(sup)抬高的影响,也不会被行内代码撑高的行框带偏。
// 首选量「标记前最后一个字符」的字体盒(浏览器给的就是该行的文字盒,取中点即行中线);
// 标记在行首、前面没有文字时,退回 .post-note-anchor(0 宽、1em 高、基线对齐的行内块)的中点。
// 两种方式都不受上标(sup)抬高、行内代码撑高行框的影响。
function lineCenter(mark, mr) {
var probe = mark.previousElementSibling;
if (!probe || !probe.classList.contains("post-note-anchor")) {
probe = mark;
}
var block =
mark.closest("p, li, td, th, dd, dt, blockquote, h1, h2, h3, h4, h5, h6") ||
mark.parentElement ||
mark;
function rectsOf(setup) {
var range = document.createRange();
setup(range);
return range.getClientRects();
}
function pick(list, fromEnd) {
var i, r;
if (fromEnd) {
for (i = list.length - 1; i >= 0; i--) {
r = list[i];
if (r.height > 0) return r;
}
} else {
for (i = 0; i < list.length; i++) {
r = list[i];
if (r.height > 0) return r;
}
}
return null;
}
var lineRect = pick(
rectsOf(function (r) {
r.setStart(block, 0);
r.setEndAfter(probe);
}),
true,
var probeRect = probe.getBoundingClientRect();
var baseline = probeRect.bottom;
var lineHeight = parseFloat(
getComputedStyle(probe.parentElement || mark).lineHeight,
);
if (!lineHeight || isNaN(lineHeight)) lineHeight = 28;
if (!lineRect || !lineRect.height) {
// 标记正好在行首时,改用「从标记到段落结尾」的第一个 rect
lineRect = pick(
rectsOf(function (r) {
r.setStartBefore(probe);
r.setEnd(block, block.childNodes.length);
}),
false,
);
var prev = probe.previousSibling;
if (prev && prev.nodeType === 3 && prev.nodeValue.length) {
var range = document.createRange();
range.setStart(prev, prev.nodeValue.length - 1);
range.setEnd(prev, prev.nodeValue.length);
var charRect = range.getBoundingClientRect();
// 最后一个字符若在上一行,charRect 底边会明显高于本行基线
if (charRect.height && charRect.bottom - baseline < lineHeight / 2) {
return charRect.top + charRect.height / 2 - mr.top;
}
}
if (!lineRect || !lineRect.height) {
return probe.getBoundingClientRect().top - mr.top;
if (probeRect.height) {
return probeRect.top + probeRect.height / 2 - mr.top;
}
return lineRect.top + lineRect.height / 2 - mr.top;
var r = mark.getBoundingClientRect();
return r.top + r.height / 2 - mr.top;
}
function layout() {