0

我正在为 HTML 表格开发一个简单的列调整大小功能。

到目前为止,该表工作正常 - Safari 除外(版本 5.1.4)。出于某种原因,Safari 将单元格宽度设为负值(!)。

此处提供 JSFiddle:simple-resize

style="width"如果从<th>元素中删除属性(或在代码检查器中禁用),则可以看到负列宽值

HTML:

<div class="tblcont" id="cont">
<table id="table1" class="pivot-table pivot-fixed-layout">
    <thead>
        <tr id="tr1">
            <th style="width: 52px;">city</th>
            <th style="width: 26px;"># c</th>
            <th style="width: 37px;"># id</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tel Aviv</td>
            <td>814</td>
            <td>1,047</td>
        </tr>
        <tr>
            <td>Natanya</td>
            <td>805</td>
            <td>1,016</td>
        </tr>
    </tbody>
    </table>
</div>

CSS:

.pivot-table.pivot-fixed-layout {
  border-collapse: collapse;
  table-layout: fixed;
  width: 0;
}

.pivot-table td, .pivot-table th {
  overflow: hidden;
  padding: 0 6px;
  border-right: 1px solid;
  border-bottom: 1px solid;
  text-overflow: ellipsis;
}

.pivot-table th {
    cursor: col-resize;
}

Javascript:

var pressed = false,
    $column,
    $table = $("table"),
    startX, startWidth,
    tableInitialWidth = $('#cont').width() - 100,
    currentTableWidth, newTableWidth;

$("table th").mousedown(function(e) {
    $column = $(this);
    pressed = true;
    startX = e.pageX;
    startWidth = $column.width();
    $column.addClass("resizing");
});

$(document).mousemove(function(e) {
    if(pressed) {

        var delta = e.pageX - startX,
            currentColumnWidth,
            newColumnWidth;

        currentColumnWidth = $column.width();
        newColumnWidth = startWidth + delta;

        currentTableWidth = $table.width();
        newTableWidth = currentTableWidth + delta;

        // no not make columns smaller than min width
        if (newColumnWidth > 2) {
            $column.width(newColumnWidth);
        }
    }
});

$(document).mouseup(function() {
    if(pressed) {
        $column.removeClass("resizing");
        pressed = false;
    }
});
4

0 回答 0