我的目标是在纯JavaScript中创建具有可调整大小的列宽度的表。见此链接。当我放大td 1的大小,然后尝试通过拖动td 3的边框使其变小时,除非再次使用td 1,否则不可能使其变小。我猜问题在于它创建了一个具有一定大小的div,在使用td 3的边框拖动时不可能更改这个div。有什么想法吗?我如何从另一个单元格中改变div宽度?
联署材料:
(function () {
var thElm;
var startOffset;
Array.prototype.forEach.call(
document.querySelectorAll("table td"),
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;
startOffset = th.offsetWidth - e.pageX;
});
th.appendChild(grip);
});
document.addEventListener('mousemove', function (e) {
if (thElm) {
thElm.style.width = startOffset + e.pageX + 'px';
}
});
document.addEventListener('mouseup', function () {
thElm = undefined;
});
})();HTML:
<table>
<thead>
<tr>
<th>th 1</th>
<th>th 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>td 1</td>
<td>td 2</td>
</tr>
<tr>
<td>td 3</td>
<td>td 4</td>
</tr>
</tbody>
</table>发布于 2018-04-14 03:50:56
您的代码正在调整单元格的大小。试着调整标题的大小,而不是单元格。
HTML:
<thead>
<tr>
<th data-header-id="col-1">th 1</th>
<th data-header-id="col-2">th 2</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column-id="col-1">td 1</td>
<td data-column-id="col-2">td 2</td>
</tr>
<tr>
<td data-column-id="col-1">td 3</td>
<td data-column-id="col-2">td 4</td>
</tr>
</tbody>
var thElm;
var startOffset;联署材料:
Array.prototype.forEach.call(
document.querySelectorAll("table td"),
function (th) {
var columnId = th.attributes["data-column-id"].value;
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 = document.querySelectorAll("[data-header-id='" + columnId + "']")[0];
console.log(thElm);
startOffset = thElm.offsetWidth - e.pageX;
});
th.appendChild(grip);
});
document.addEventListener('mousemove', function (e) {
if (thElm) {
thElm.style.width = startOffset + e.pageX + 'px';
}
});
document.addEventListener('mouseup', function () {
thElm = undefined;
});这是你的一把小提琴叉,显示了更新的代码:http://jsfiddle.net/54n2rke9/12/
更新:一种替代方法
在这里,不需要更改原始的HTML。
Array.prototype.forEach.call(
document.querySelectorAll("table td"),
function (th) {
th.style.position = 'relative';
var cellIndex = th.cellIndex;
...
grip.addEventListener('mousedown', function (e) {
thElm = document.querySelectorAll("th")[cellIndex];
startOffset = thElm.offsetWidth - e.pageX;
});
th.appendChild(grip);
});https://stackoverflow.com/questions/49826763
复制相似问题