js实现自定义修改网页中表格信息
项目中的打印页面,为提高用户体验,需要增自定修改表格内容的功能,以下是使用示意图(双击td标签部分的内容,可自定义修改):
以下是js插件源码,存为edit.js文件:
1 var tbl, tbt;
2
3 var body = document.getElementsByTagName('body');
4
5 var tb = document.getElementsByTagName("table");
6 tbl = tb[0].offsetLeft;
7 tbt = tb[0].offsetTop;
8
9 var list = httpCollectionToArray(document.getElementsByTagName("td"));
10
11 list.forEach(function (value) {
12 value.addEventListener('dblclick', function () {
13 blurEdit();
14 var left = tbl + value.offsetLeft - 5;
15 var top = tbt + value.offsetTop - 5;
16 var width = value.offsetWidth + 10;
17 var height = value.offsetHeight + 10;
18 var div = document.createElement('div');
19 div.style.cssText = "position:absolute;width:" + width + "px;height:" + height + "px;border:2px solid #000;top:" + top + ";left:" + left + ";";
20 var textarea = document.createElement('textarea');
21 textarea.setAttribute("class", "editTextarea");
22 textarea.style.cssText = "width:" + width + "px;height:" + height + "px;resize:none;";
23
24 var text = document.createTextNode(value.innerText);
25 textarea.appendChild(text);
26 div.appendChild(textarea);
27
28 textarea.addEventListener('blur', function () {
29 var text = document.getElementsByClassName('editTextarea')[0].value;
30 // 转换文本中的回车符和空格符
31 text = text.replace(/\n/g, "<br/>");
32 text = text.replace(/\s/g, " ");
33 value.innerHTML = text;
34 body[0].removeChild(div);
35 });
36
37 body[0].appendChild(div);
38 document.getElementsByClassName('editTextarea')[0].focus();
39 });
40 });
41
42 function blurEdit() {
43 var focus = httpCollectionToArray(document.getElementsByClassName('editTextarea'));
44 focus.forEach(function (value) {
45 value.blur();
46 });
47 }
48
49 function httpCollectionToArray(collections) {
50 var array = [];
51 for (var i = 0; i < collections.length; i++) {
52 array[i] = collections[i];
53 }
54 return array;
55 }
使用方法:在对应的前端页面引入edit.js文件,如下:
1 <script src="<c:url value="/staticmedia/scripts/edit.js"/>"