巧妙解决网页批注Y轴重叠:自适应算法详解
本文介绍一种类似Word的网页批注功能实现方案,重点在于如何通过算法避免批注垂直方向上的重叠。 核心是设计一个算法,根据已有的批注信息,智能计算新批注的最佳垂直位置。
理想的批注布局需兼顾两种情况:批注间距较大时,新批注应尽可能靠近关联文本;间距较小时,新批注应紧挨前一个批注,但不能重叠。
我们采用绝对定位(absolute positioning)和JavaScript实现。 将每个批注信息存储在一个数组中,每个对象包含 top
属性(距离页面顶部的距离)和 height
属性(批注高度)。例如:
[ { top: 100, height: 200 }, { top: 800, height: 200 }, { top: 820, height: 200 }, { top: 1020, height: 200 }, ]
通过遍历数组,计算每个批注的实际 top
值。 算法核心在于使用 Math.max
函数,确保新批注的 top
值不小于前一个批注底部,也不小于关联文本的 top
值。 代码示例如下:
const arr = [ { top: 100, height: 200 }, { top: 800, height: 200 }, { top: 820, height: 200 }, { top: 1020, height: 200 }, { top: 1430, height: 180 }, ]; arr.reduce((s, n, i) => { n.currentTop = Math.max(n.top, (s.currentTop || s.top) + s.height); return n; }); console.log(arr);
这段代码利用 reduce
方法迭代数组, currentTop
属性存储当前批注的实际顶部位置。 Math.max
函数有效防止批注重叠。 此算法类似瀑布流布局,但增加了对关联文本位置的考量。 最终计算出的 currentTop
值将用于设置新批注的Y轴位置,实现批注的自适应布局。