Notes: anchor start point on the line's vertical center
This commit is contained in:
+64
-1
@@ -23,6 +23,69 @@
|
||||
});
|
||||
}
|
||||
|
||||
// 取注释所在「行」的垂直中点。
|
||||
// 做法:用 Range 从段落开头量到 .post-note-anchor(零尺寸基准点,贴在行基线上),
|
||||
// 它的最后一个 rect 就是标记所在那一行的文字片段,取其中点即可。
|
||||
// 这样既不受上标(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,
|
||||
);
|
||||
|
||||
if (!lineRect || !lineRect.height) {
|
||||
// 标记正好在行首时,改用「从标记到段落结尾」的第一个 rect
|
||||
lineRect = pick(
|
||||
rectsOf(function (r) {
|
||||
r.setStartBefore(probe);
|
||||
r.setEnd(block, block.childNodes.length);
|
||||
}),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
if (!lineRect || !lineRect.height) {
|
||||
return probe.getBoundingClientRect().top - mr.top;
|
||||
}
|
||||
|
||||
return lineRect.top + lineRect.height / 2 - mr.top;
|
||||
}
|
||||
|
||||
function layout() {
|
||||
var main = document.getElementById("content");
|
||||
if (!main) return;
|
||||
@@ -62,7 +125,7 @@
|
||||
note.style.width = width + "px";
|
||||
|
||||
var height = note.offsetHeight;
|
||||
var lineY = markRect.top - mr.top + markRect.height / 2;
|
||||
var lineY = lineCenter(mark, mr);
|
||||
|
||||
var top = Math.max(0, lineY - 6);
|
||||
if (top < bottom + MIN_STACK) top = bottom + MIN_STACK;
|
||||
|
||||
Reference in New Issue
Block a user