73 lines
2.4 KiB
JavaScript
73 lines
2.4 KiB
JavaScript
// 边注定位:宽屏时把 .post-note 放到正文左右两侧的空白处,
|
|
// 窄屏时交还给 CSS(虚线框内嵌)。
|
|
(function () {
|
|
var WIDE = 1280; // 与 CSS 的 @media (min-width: 80rem) 保持一致
|
|
var MIN_GAP = 12; // 同一侧两条注释之间的最小垂直间距
|
|
|
|
function layout() {
|
|
var main = document.querySelector("main.notes-page");
|
|
if (!main) return;
|
|
|
|
var notes = Array.prototype.slice.call(
|
|
main.querySelectorAll(".post-note"),
|
|
);
|
|
if (!notes.length) return;
|
|
|
|
if (window.innerWidth < WIDE) {
|
|
main.classList.remove("notes-active");
|
|
notes.forEach(function (note) {
|
|
note.classList.remove("placed");
|
|
note.removeAttribute("data-side");
|
|
note.style.top = "";
|
|
});
|
|
return;
|
|
}
|
|
|
|
main.classList.add("notes-active");
|
|
|
|
var mainTop = main.getBoundingClientRect().top;
|
|
var sideBottom = { left: -Infinity, right: -Infinity };
|
|
|
|
notes.forEach(function (note, i) {
|
|
var mark = note.previousElementSibling;
|
|
if (!mark || !mark.classList.contains("post-note-mark")) {
|
|
mark = note;
|
|
}
|
|
|
|
var side = i % 2 === 0 ? "right" : "left";
|
|
note.setAttribute("data-side", side);
|
|
note.classList.add("placed");
|
|
|
|
var anchorTop = mark.getBoundingClientRect().top - mainTop;
|
|
var height = note.offsetHeight;
|
|
|
|
var top = Math.max(0, anchorTop - 6);
|
|
if (top < sideBottom[side] + MIN_GAP) {
|
|
top = sideBottom[side] + MIN_GAP;
|
|
}
|
|
|
|
note.style.top = top + "px";
|
|
sideBottom[side] = top + height;
|
|
});
|
|
}
|
|
|
|
var timer;
|
|
function schedule() {
|
|
clearTimeout(timer);
|
|
timer = setTimeout(layout, 100);
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", layout);
|
|
window.addEventListener("load", layout);
|
|
window.addEventListener("resize", schedule);
|
|
if (document.fonts && document.fonts.ready) {
|
|
document.fonts.ready.then(layout);
|
|
}
|
|
if (window.ResizeObserver) {
|
|
document.addEventListener("DOMContentLoaded", function () {
|
|
var content = document.querySelector("main.notes-page .content");
|
|
if (content) new ResizeObserver(schedule).observe(content);
|
|
});
|
|
}
|
|
})();
|