首页  编辑  

JS 表格操作

Tags: /计算机文档/网页制作/   Date Created:
下面的代码,都是基于一个div contentEditable,对齐进行操作的:
插入表格
function insertNodeAtCaret(node) {
	var sel, range;
	if (window.getSelection) {
		sel = window.getSelection();
		if (sel.getRangeAt && sel.rangeCount) {
			range = sel.getRangeAt(0);
			range.deleteContents();
			range.insertNode(node);

			range.setStartAfter(node);
			range.setEndAfter(node);
			sel.removeAllRanges();
			sel.addRange(range);
		}
	} else if (document.selection && document.selection.createRange) {
		document.selection.createRange().innerHTML = node.innerHTML;
	}
}

function insertTable() {
	var xy = prompt("请输入表格行x列数\n例如 5,3 表示插入5行3列的表格", "5,3", null);
	if (xy == null) return;
	xy = xy.replaceAll(" ", "").split(",");

	var table = document.createElement("table");
	table.setAttribute("border", 1);
	for (var i = 0; i < xy[0]; i++) {
		var row = table.insertRow();
		for (j = 0; j < xy[1]; j++) {
			row.insertCell();
		}
	}
	insertNodeAtCaret(table);
}
在当前单元格下面插入行
function insertTableRow() {
	var selection = window.getSelection();
	if (selection.rangeCount <=0) return;
	var range = selection.getRangeAt(0);
	if (!range.collapsed) return;
	var container = range.commonAncestorContainer;
	if (container.nodeType === 3) container = container.parentNode;
	var table = container.closest('table');
	if (!table) return;
	var row = container.closest('tr');
	var cell = container.closest('td, th');
	if (!cell) return;
	var rowIndex = cell.parentNode.rowIndex;
	var cellIndex = cell.cellIndex;
	var newRow = table.insertRow(rowIndex + 1);
	for (var i=0; i<row.cells.length; i++) {
		newRow.insertCell();
	}
}
在当前单元格前插入列
function insertTableColumn() {
	var selection = window.getSelection();
	if (selection.rangeCount <=0) return;
	var range = selection.getRangeAt(0);
	if (!range.collapsed) return;
	var container = range.commonAncestorContainer;
	if (container.nodeType === 3) container = container.parentNode;
	var table = container.closest('table');
	if (!table) return;
	var row = container.closest('tr');
	var cell = container.closest('td, th');
	if (!cell) return;
	var rowIndex = cell.parentNode.rowIndex;
	var cellIndex = cell.cellIndex;
	for (var i=0; i<table.rows.length; i++) {
		table.rows[i].insertCell(cellIndex)
	}
}