feat(iframe): 添加父窗口与iframe间的页面跳转API

暴露OCDIframeAPI接口,包含getFirstVisiblePageNo和gotoPage方法
移除demo.html中重复实现的页面跳转逻辑,改用新API
This commit is contained in:
hanshiyang committed 2025-12-02 11:26:54 +08:00
1 parent 27c85de1c4
commit 1335932afa
3 files changed
+506 -480

No files matched your search

+19 -44
View File
@@ -148,7 +148,14 @@
actions.className = 'bookmark-actions'
const jumpBtn = document.createElement('button')
jumpBtn.textContent = '跳转'
jumpBtn.onclick = () => navigateToPage(item.page)
jumpBtn.onclick = () => {
const api = editorFrame.contentWindow && editorFrame.contentWindow.OCDIframeAPI
if (api && typeof api.gotoPage === 'function') {
api.gotoPage(item.page)
} else {
alert('子页面未提供跳转 API')
}
}
const editBtn = document.createElement('button')
editBtn.textContent = '编辑'
editBtn.onclick = () => {
@@ -185,52 +192,20 @@
addBookmarkBtn.onclick = () => {
const name = getNextBookmarkName()
const page = getFirstVisiblePageNo()
let page = 1
try {
const api = editorFrame.contentWindow && editorFrame.contentWindow.OCDIframeAPI
if (api && typeof api.getFirstVisiblePageNo === 'function') {
page = api.getFirstVisiblePageNo()
} else {
console.warn('[demo] 子页面未暴露 getFirstVisiblePageNo,默认使用第1页')
}
} catch (e) {
console.warn('[demo] 获取当前可见页失败,默认第1页', e)
}
addBookmark(name, page)
}
function getFirstVisiblePageNo() {
const doc = editorFrame.contentDocument || editorFrame.contentWindow?.document
if (!doc) return 1
const iframeRect = editorFrame.getBoundingClientRect()
const canvases = Array.from(doc.querySelectorAll('canvas[data-index]'))
if (!canvases.length) return 1
const visible = canvases
.map(c => {
const rect = c.getBoundingClientRect()
const overlapY = Math.min(rect.bottom, iframeRect.bottom) - Math.max(rect.top, iframeRect.top)
return { c, rect, overlapY }
})
.filter(x => x.overlapY > 0)
.sort((a, b) => a.rect.top - b.rect.top)
let chosen = visible.length ? visible[0].c : null
if (!chosen) {
chosen = canvases.sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top)[0]
}
const idxStr = chosen?.getAttribute('data-index') || '0'
const idx = parseInt(idxStr, 10)
return Number.isFinite(idx) ? idx + 1 : 1
}
function navigateToPage(page) {
const doc = editorFrame.contentDocument || editorFrame.contentWindow?.document
if (!doc) return
const target0 = doc.querySelector(`canvas[data-index="${page - 1}"]`)
const target1 = doc.querySelector(`canvas[data-index="${page}"]`)
const canvas = target0 || target1
if (!canvas) {
alert(`未找到第${page}页`)
return
}
try {
canvas.scrollIntoView({ behavior: 'smooth', block: 'center' })
const evt = new MouseEvent('mousedown', { bubbles: true })
canvas.dispatchEvent(evt)
} catch (e) {
console.warn('跳转页失败', e)
}
}
editorFrame.addEventListener('load', () => {
renderBookmarks()