在 KindEditor 編輯器中插入多張圖片,點擊任意圖片選中時,編輯器內容區滾動條突然跳轉到頂部,導致編輯體驗極差。
經過源碼排查,問題出在位置計算函數 `K.pos()`(或 `editor.cmd.range` 相關邏輯)中:
pos : function() {
var self = this, node = self[0], x = 0, y = 0;
if (node) {
if (node.getBoundingClientRect) {
var box = node.getBoundingClientRect(),
pos = _getScrollPos(self.doc);
x = box.left + pos.x;
y = box.top + pos.y; // ★ 關鍵行:box.top 在點擊圖片時變為負數
} else { ... }
}
return {x: _round(x), y: _round(y)};
}
當點擊 `` 時,`getBoundingClientRect().top` 返回相對視口的坐標,若圖片在可視區上方(或因邊距/定位導致),`top` 為負數,加上滾動偏移 `pos.y` 後導致計算出的絕對位置錯誤,進而觸發編輯器錯誤的滾動定位。
// 在 kindeditor.js 或 kindeditor-min.js 中找到 pos 函數
y = (box.top < 0 ? 0 : box.top) + pos.y; // 修正:負數歸零
// 或更嚴謹:
y = Math.max(0, box.top) + pos.y;
原理:`box.top` 為負數時說明元素在視口上方,實際文檔坐標不應小於 0,強制歸零修正。
if (node.tagName === 'IMG') {
// 圖片特殊處理:使用 offsetTop 累加或 getBoundingClientRect 修正
y = Math.max(0, box.top) + pos.y;
} else {
y = box.top + pos.y;
}
官方較新版本(4.1.11+)已修復類似問題,建議直接升級替換核心文件。
KindEditor `pos()` 函數未處理 `getBoundingClientRect().top` 為負數的邊界情況,導致點擊視口上方圖片時計算錯誤文檔坐標,觸發錯誤滾動。通過 `Math.max(0, box.top)` 修正即可徹底解決,屬於典型的邊界條件缺陷。