1 回答
TA贡献1824条经验 获得超8个赞
您的代码不起作用,因为在调用回调时,事件侦听器仅附加到最初的两列$(document).ready。一个简单的解决方案是 AddListeners()每次插入新列时调用,如下所示:
function AddListeners() {
var thElm;
var startOffsetX;
var startOffsetY;
Array.prototype.forEach.call(
document.querySelectorAll("table th"),
function(th) {
th.style.position = 'relative';
var grip = document.createElement('div');
grip.innerHTML = " ";
grip.style.top = 0;
grip.style.right = 0;
grip.style.bottom = 0;
grip.style.width = '5px';
grip.style.position = 'absolute';
grip.style.cursor = 'col-resize';
grip.addEventListener('mousedown', function(e) {
thElm = th;
startOffsetX = th.offsetWidth - e.pageX;
startOffsetY = th.offsetHeight - e.pageY;
});
th.appendChild(grip);
});
document.addEventListener('mousemove', function(e) {
if (thElm) {
thElm.style.width = startOffsetX + e.pageX + 'px';
thElm.style.height = startOffsetY + e.pageY + 'px';
}
});
document.addEventListener('mouseup', function() {
thElm = undefined;
});
};
$(document).ready(function() {
AddListeners();
})
var iter = 2;
function AddColumn() {
var myform = $('#myTable');
myform.find('tr').each(function() {
var trow = $(this);
iter += 1;
if (trow.index() === 0) {
trow.append('<th><div style="top: 0px; right: 0px; bottom: 0px; width: 5px; position: absolute; cursor: col-resize;"> </div>th ' + iter + '</th>');
} else {
trow.append('<td>th ' + iter + '</td>');
}
});
AddListeners();
}
table {
border-width: 1px;
border-style: solid;
border-color: black;
border-collapse: collapse;
}
table td {
border-width: 1px;
border-style: solid;
border-color: black;
}
table th {
border-width: 1px;
border-style: solid;
border-color: black;
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a onclick="AddColumn()">Add column</a>
<table id="myTable">
<thead>
<tr>
<th>th 1</th>
<th>th 2</th>
</tr>
</thead>
</table>
但这个解决方案很丑陋,因为它会重做为早期存在的列添加的侦听器。更好的解决方案需要您将每列的事件附加过程与回调中解耦AddListeners()
,并分别在Array.prototype.forEach.call
和 中 调用它AddColumn()
。但这是另一个问题了。
添加回答
举报