Files
yunzerwebsiteallinone/uniapp/utils/table-editor.js
T
2026-08-15 22:16:58 +08:00

109 lines
2.9 KiB
JavaScript

/** H5 富文本表格 DOM 操作 */
export function createEmptyCell(tagName = 'td') {
const cell = document.createElement(tagName)
cell.innerHTML = '<p><br></p>'
return cell
}
export function buildTableHtml(rows = 3, cols = 3) {
let html = '<table><tbody>'
for (let r = 0; r < rows; r += 1) {
html += '<tr>'
for (let c = 0; c < cols; c += 1) {
html += '<td><p><br></p></td>'
}
html += '</tr>'
}
html += '</tbody></table><p><br></p>'
return html
}
export function getCurrentCell(editorEl) {
const sel = window.getSelection()
if (!sel || sel.rangeCount === 0) return null
let node = sel.anchorNode
if (node?.nodeType === Node.TEXT_NODE) node = node.parentElement
const cell = node?.closest?.('td, th')
if (!cell || !editorEl?.contains(cell)) return null
return cell
}
export function addRowBefore(cell) {
const row = cell.closest('tr')
const newRow = row.cloneNode(true)
newRow.querySelectorAll('td, th').forEach((item) => {
item.innerHTML = '<p><br></p>'
item.removeAttribute('colspan')
item.removeAttribute('rowspan')
})
row.before(newRow)
return newRow.cells[cell.cellIndex] || newRow.cells[0]
}
export function addRowAfter(cell) {
const row = cell.closest('tr')
const newRow = row.cloneNode(true)
newRow.querySelectorAll('td, th').forEach((item) => {
item.innerHTML = '<p><br></p>'
item.removeAttribute('colspan')
item.removeAttribute('rowspan')
})
row.after(newRow)
return newRow.cells[cell.cellIndex] || newRow.cells[0]
}
export function deleteRow(cell) {
const row = cell.closest('tr')
const section = row?.parentElement
if (!row || !section || section.querySelectorAll('tr').length <= 1) return null
const focusCell =
row.nextElementSibling?.cells[cell.cellIndex] ||
row.previousElementSibling?.cells[cell.cellIndex] ||
null
row.remove()
return focusCell
}
export function addColBefore(cell) {
const index = cell.cellIndex
const table = cell.closest('table')
table.querySelectorAll('tr').forEach((row) => {
const refCell = row.cells[index]
if (!refCell) return
refCell.before(createEmptyCell(refCell.tagName.toLowerCase()))
})
return cell.parentElement.cells[index]
}
export function addColAfter(cell) {
const index = cell.cellIndex
const table = cell.closest('table')
table.querySelectorAll('tr').forEach((row) => {
const refCell = row.cells[index]
if (!refCell) return
refCell.after(createEmptyCell(refCell.tagName.toLowerCase()))
})
return cell.parentElement.cells[index + 1]
}
export function deleteCol(cell) {
const index = cell.cellIndex
const table = cell.closest('table')
if (cell.parentElement.cells.length <= 1) return null
let focusCell = null
table.querySelectorAll('tr').forEach((row) => {
const target = row.cells[index]
if (!target) return
if (row === cell.parentElement) {
focusCell = row.cells[index + 1] || row.cells[index - 1] || null
}
target.remove()
})
return focusCell
}
export function deleteTable(cell) {
cell.closest('table')?.remove()
}