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()
。但這是另一個問題了。
添加回答
舉報