js实现自定义修改网页中表格信息

时间:2022-11-04 05:42:23

项目中的打印页面,为提高用户体验,需要增自定修改表格内容的功能,以下是使用示意图(双击td标签部分的内容,可自定义修改):js实现自定义修改网页中表格信息

以下是js插件源码,存为edit.js文件:

 var tbl, tbt;

 var body = document.getElementsByTagName('body');

 var tb = document.getElementsByTagName("table");
tbl = tb[0].offsetLeft;
tbt = tb[0].offsetTop; var list = httpCollectionToArray(document.getElementsByTagName("td")); list.forEach(function (value) {
value.addEventListener('dblclick', function () {
blurEdit();
var left = tbl + value.offsetLeft - 5;
var top = tbt + value.offsetTop - 5;
var width = value.offsetWidth + 10;
var height = value.offsetHeight + 10;
var div = document.createElement('div');
div.style.cssText = "position:absolute;width:" + width + "px;height:" + height + "px;border:2px solid #000;top:" + top + ";left:" + left + ";";
var textarea = document.createElement('textarea');
textarea.setAttribute("class", "editTextarea");
textarea.style.cssText = "width:" + width + "px;height:" + height + "px;resize:none;"; var text = document.createTextNode(value.innerText);
textarea.appendChild(text);
div.appendChild(textarea); textarea.addEventListener('blur', function () {
var text = document.getElementsByClassName('editTextarea')[0].value;
       // 转换文本中的回车符和空格符
text = text.replace(/\n/g, "<br/>");
text = text.replace(/\s/g, "&nbsp;");
value.innerHTML = text;
body[0].removeChild(div);
}); body[0].appendChild(div);
document.getElementsByClassName('editTextarea')[0].focus();
});
}); function blurEdit() {
var focus = httpCollectionToArray(document.getElementsByClassName('editTextarea'));
focus.forEach(function (value) {
value.blur();
});
} function httpCollectionToArray(collections) {
var array = [];
for (var i = 0; i < collections.length; i++) {
array[i] = collections[i];
}
return array;
}

使用方法:在对应的前端页面引入edit.js文件,如下:

 <script src="<c:url value="/staticmedia/scripts/edit.js"/>"