使用 jQuery 调整表格列的大小

发布于 2024-11-10 03:52:07 字数 1539 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

甚是思念 2024-11-17 03:52:07

:-) 一旦我发现自己处于同样的情况,没有符合我要求的 jQuery 插件,所以我花了一些时间开发自己的插件: col可调整大小
 

关于 colResizable

colResizing 是一个免费的 jQuery 插件,用于通过手动拖动来调整表格列的大小。它与鼠标和触摸设备兼容,并具有一些不错的功能,例如页面刷新或回发后的布局持久性。它适用于基于百分比和基于像素的表格布局。

它体积很小(colResabilized 1.0 仅 2kb),并且与所有主流浏览器(IE7+、Firefox、Chrome 和 Opera)完全兼容。

在此处输入图像描述

功能

由于没有找到具有以下列出功能的其他类似插件,因此开发了 colResizable

  • :与鼠标和触摸兼容设备(PC、平板电脑和移动电话)
  • 与基于百分比和基于像素的表格布局兼容
  • 调整列大小不会改变表格总宽度(可选)
  • 无需外部资源(例如图像或样式表)
  • 页面刷新或回发后可选的布局持久性
  • 自定义列锚点
  • 数量 小占用空间
  • 跨浏览器兼容性(IE7+、Chrome、Safari、Firefox)
  • 事件

与其他插件的比较

colRessized 是用于调整表格列大小的最精美的插件。它具有大量的定制可能性,并且还与触摸设备兼容。但最有趣的功能可能是它与基于像素的表格布局和流体百分比表格布局兼容,这使得 colResized 成为最佳选择。但是,这是什么意思呢?

如果表格的宽度设置为 90%,并且使用 colResizable 修改列宽,则当调整浏览器大小时,列宽也会按比例调整大小。虽然其他插件的行为确实很奇怪,但 colResizable 却按照预期完成了它的工作。

colResizable 还与表 max-width 属性兼容:如果所有列的总和超过表的 max-width,它们会自动修复和更新。

与其他插件相比,另一个很大的优点是它与页面刷新、回发甚至部分回发(如果表位于 updatePanel 内部)兼容。它与所有主要浏览器(IE7+、Firefox、Chrome 和 Opera)兼容,而其他插件则无法使用旧版 IE。

请参阅示例JSFiddle

代码示例

$("#sample").colResizable({
        liveDrag:true
});

:-) Once I found myself in the same situation, there was no jQuery plugin matching my requeriments, so I spend some time developing my own one: colResizable
 

About colResizable

colResizable is a free jQuery plugin to resize table columns dragging them manually. It is compatible with both mouse and touch devices and has some nice features such as layout persistence after page refresh or postback. It works with both percentage and pixel-based table layouts.

It is tiny in size (colResizable 1.0 is only 2kb) and it is fully compatible with all major browsers (IE7+, Firefox, Chrome and Opera).

enter image description here

Features

colResizable was developed since no other similar plugin with the below listed features was found:

  • Compatible with mouse and touch devices (PC, tablets, and mobile phones)
  • Compatibility with both percentage and pixel-based table layouts
  • Column resizing not altering total table width (optional)
  • No external resources needed (such as images or stylesheets)
  • Optional layout persistence after page refresh or postback
  • Customization of column anchors
  • Small footprint
  • Cross-browser compatibility (IE7+, Chrome, Safari, Firefox)
  • Events

Comparison with other plugins

colResizable is the most polished plugin to resize table columns out there. It has plenty of customization possibilities and it is also compatible with touch devices. But probably the most interesting feature which is making colResizable the greatest choice is that it is compatible with both pixel-based and fluid percentage table layouts. But, what does it mean?

If the width of a table is set to, lets say 90%, and the column widths are modified using colResizable, when the browser is resized columns widths are resized proportionally. While other plugins does behave odd, colResizable does its job just as expected.

colResizable is also compatible with table max-width attribute: if the sum of all columns exceed the table's max-width, they are automatically fixed and updated.

Another great advantage compared with other plugins is that it is compatible with page refresh, postbacks and even partial postbacks if the table is located inside of an updatePanel. It is compatible with all major browsers (IE7+, Firefox, Chrome and Opera), while other plugins fail with old IE versions.

See samples and JSFiddle.

Code sample

$("#sample").colResizable({
        liveDrag:true
});
芸娘子的小脾气 2024-11-17 03:52:07

所以我开始编写自己的,现在只是简单的功能,下周将开始工作...... http:// jsfiddle.net/ydTCZ/

So I started writing my own, just bare bones functionality for now, will be working on it next week... http://jsfiddle.net/ydTCZ/

强者自强 2024-11-17 03:52:07

这是一个简短的完整 html 示例。查看演示 http://jsfiddle.net/CU585/

<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>

Here's a short complete html example. See demo http://jsfiddle.net/CU585/

<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>
等待圉鍢 2024-11-17 03:52:07

或者尝试我的解决方案: http://robau.wordpress.com/2011/08/16/unobtrusive-table-column-resize-with-jquery-as-plugin/ :)

(function( $ )
    {
        $.fn.simpleResizableTable = function() 
        { 
            /**
             * Author: Rob Audenaerde
             * Version: plugin version 0.5
             */
            
            $("<style type='text/css'> .srt-draghandle.dragged{border-left: 1px solid #333;}</style>").appendTo("head");
            $("<style type='text/css'> .srt-draghandle{ position: absolute; z-index:5; width:5px; cursor:e-resize;}</style>").appendTo("head");

            function resetTableSizes (table, change, columnIndex)
            {
                //calculate new width;
                var tableId = table.attr('id'); 
                var myWidth = $('#'+tableId+' TR TH').get(columnIndex).offsetWidth;
                var newWidth = (myWidth+change)+'px';

                $('#'+tableId+' TR').each(function() 
                {
                    $(this).find('TD').eq(columnIndex).css('width',newWidth);
                    $(this).find('TH').eq(columnIndex).css('width',newWidth);
                });
                resetSliderPositions(table);
            };

            function resetSliderPositions(table)
            {
                var tableId = table.attr('id'); 
                //put all sliders on the correct position
                table.find(' TR:first TH').each(function(index)
                { 
                    var td = $(this);
                    var newSliderPosition = td.offset().left+td.outerWidth();
                    $("#"+tableId+"_id"+(index+1)).css({  left:   newSliderPosition , height: table.height() + 'px'}  );
                });
            }


            function makeResizable(table)
            {       
                //get number of columns
                var numberOfColumns = table.find('TR:first TH').size();

                //id is needed to create id's for the draghandles
                var tableId = table.attr('id'); 
                
                for (var i=0; i<=numberOfColumns; i++)
                {
                    //enjoy this nice chain :)
                    $('<div class="srt-draghandle" id="'+tableId+'_id'+i+'"></div>').insertBefore(table).data('tableid', tableId).data('myindex',i).draggable(
                    { axis: "x",
                      start: function () 
                      {
                        var tableId = ($(this).data('tableid'));
                        $(this).toggleClass( "dragged" );
                        //set the height of the draghandle to the current height of the table, to get the vertical ruler
                        $(this).css({ height: $('#'+tableId).height() + 'px'} );
                      },
                      stop: function (event, ui) 
                      {
                        var tableId = ($(this).data('tableid'));
                        $( this ).toggleClass( "dragged" ); 
                        var oldPos  = ($( this ).data("draggable").originalPosition.left);
                        var newPos = ui.position.left;
                        var index =  $(this).data("myindex");
                        resetTableSizes($('#'+tableId), newPos-oldPos, index-1);
                      }       
                    }
                    );;
                };
                resetSliderPositions(table);
                return table;
            };

            return this.each(function() 
            {
                makeResizable($(this));
            });
        };
    })( jQuery );

Or try my solution: http://robau.wordpress.com/2011/08/16/unobtrusive-table-column-resize-with-jquery-as-plugin/ :)

(function( $ )
    {
        $.fn.simpleResizableTable = function() 
        { 
            /**
             * Author: Rob Audenaerde
             * Version: plugin version 0.5
             */
            
            $("<style type='text/css'> .srt-draghandle.dragged{border-left: 1px solid #333;}</style>").appendTo("head");
            $("<style type='text/css'> .srt-draghandle{ position: absolute; z-index:5; width:5px; cursor:e-resize;}</style>").appendTo("head");

            function resetTableSizes (table, change, columnIndex)
            {
                //calculate new width;
                var tableId = table.attr('id'); 
                var myWidth = $('#'+tableId+' TR TH').get(columnIndex).offsetWidth;
                var newWidth = (myWidth+change)+'px';

                $('#'+tableId+' TR').each(function() 
                {
                    $(this).find('TD').eq(columnIndex).css('width',newWidth);
                    $(this).find('TH').eq(columnIndex).css('width',newWidth);
                });
                resetSliderPositions(table);
            };

            function resetSliderPositions(table)
            {
                var tableId = table.attr('id'); 
                //put all sliders on the correct position
                table.find(' TR:first TH').each(function(index)
                { 
                    var td = $(this);
                    var newSliderPosition = td.offset().left+td.outerWidth();
                    $("#"+tableId+"_id"+(index+1)).css({  left:   newSliderPosition , height: table.height() + 'px'}  );
                });
            }


            function makeResizable(table)
            {       
                //get number of columns
                var numberOfColumns = table.find('TR:first TH').size();

                //id is needed to create id's for the draghandles
                var tableId = table.attr('id'); 
                
                for (var i=0; i<=numberOfColumns; i++)
                {
                    //enjoy this nice chain :)
                    $('<div class="srt-draghandle" id="'+tableId+'_id'+i+'"></div>').insertBefore(table).data('tableid', tableId).data('myindex',i).draggable(
                    { axis: "x",
                      start: function () 
                      {
                        var tableId = ($(this).data('tableid'));
                        $(this).toggleClass( "dragged" );
                        //set the height of the draghandle to the current height of the table, to get the vertical ruler
                        $(this).css({ height: $('#'+tableId).height() + 'px'} );
                      },
                      stop: function (event, ui) 
                      {
                        var tableId = ($(this).data('tableid'));
                        $( this ).toggleClass( "dragged" ); 
                        var oldPos  = ($( this ).data("draggable").originalPosition.left);
                        var newPos = ui.position.left;
                        var index =  $(this).data("myindex");
                        resetTableSizes($('#'+tableId), newPos-oldPos, index-1);
                      }       
                    }
                    );;
                };
                resetSliderPositions(table);
                return table;
            };

            return this.each(function() 
            {
                makeResizable($(this));
            });
        };
    })( jQuery );
你与昨日 2024-11-17 03:52:07

虽然很晚了,但希望它仍然对某人有帮助:

这里和其他帖子中的许多评论都与设置初始大小有关。

我使用了 jqueryUi.Ressized
初始宽度应在每个“”内定义第一行标记 (< TR >)。这与 colResibility 推荐的不同; colResizable 禁止在第一行定义宽度,我必须在“”中定义宽度与 jqueryresizing 不一致的标签。

下面的代码片段非常简洁,比通常的示例更容易阅读:

$("#Content td").resizable({
    handles: "e, s",
    resize: function (event, ui) {
        var sizerID = "#" + $(event.target).attr("id");
        $(sizerID).width(ui.size.width);
    }
});

内容是我的表的 id。
句柄 (e, s) 定义插件可以更改大小的方向。
你必须有jquery-ui的css的链接,否则它将无法工作。

Although very late, hope it still helps someone:

Many of comments here and in other posts are concerned about setting initial size.

I used jqueryUi.Resizable.
Initial widths shall be defined within each "< td >" tag at first line (< TR >). This is unlike what colResizable recommends; colResizable prohibits defining widths at first line, there I had to define widths in "< col>" tag which wasn't consikstent with jqueryresizable.

the following snippet is very neat and easier to read than usual samples:

$("#Content td").resizable({
    handles: "e, s",
    resize: function (event, ui) {
        var sizerID = "#" + $(event.target).attr("id");
        $(sizerID).width(ui.size.width);
    }
});

Content is id of my table.
Handles (e, s) define in which directions the plugin can change the size.
You must have a link to css of jquery-ui, otherwise it won't work.

烛影斜 2024-11-17 03:52:07

我尝试添加到@user686605的工作中:

1)将光标更改为在边界处调整大小

2)修复了调整大小时突出显示文本的问题

我在这两个方面都部分成功。也许更擅长 CSS 的人可以帮助推动这一进程?

http://jsfiddle.net/telefonica/L2f7F/4/

HTML

<!--Click on th and drag...-->
<table>
    <thead>
        <tr>
            <th><div class="noCrsr">th 1</div></th>
            <th><div class="noCrsr">th 2</div></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>td 1</td>
            <td>td 2</td>
        </tr>
    </tbody>
</table>

<强>JS

$(function() {
    var pressed = false;
    var start = undefined;
    var startX, startWidth;

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

    $(document).mousemove(function(e) {
        if(pressed) {
            $(start).width(startWidth+(e.pageX-startX));
        }
    });

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

<强>CSS

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: 1px;
    border-style: solid;
    border-color: black;
    background-color: green;
    cursor: col-resize;
}

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

.noCrsr {
    cursor: default;
    margin-right: +5px;
}

.noSelect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

I tried to add to @user686605's work:

1) changed the cursor to col-resize at the th border

2) fixed the highlight text issue when resizing

I partially succeeded at both. Maybe someone who is better at CSS can help move this forward?

http://jsfiddle.net/telefonica/L2f7F/4/

HTML

<!--Click on th and drag...-->
<table>
    <thead>
        <tr>
            <th><div class="noCrsr">th 1</div></th>
            <th><div class="noCrsr">th 2</div></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>td 1</td>
            <td>td 2</td>
        </tr>
    </tbody>
</table>

JS

$(function() {
    var pressed = false;
    var start = undefined;
    var startX, startWidth;

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

    $(document).mousemove(function(e) {
        if(pressed) {
            $(start).width(startWidth+(e.pageX-startX));
        }
    });

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

CSS

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: 1px;
    border-style: solid;
    border-color: black;
    background-color: green;
    cursor: col-resize;
}

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

.noCrsr {
    cursor: default;
    margin-right: +5px;
}

.noSelect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
自我难过 2024-11-17 03:52:07

我今天尝试了几种解决方案,最适合我的一个是 Jo-Geek/jQuery-ResizableColumns< /a>.它非常简单,但它可以处理放置在弹性容器中的表,而其他许多容器都无法做到这一点。

<table class="resizable">
</table>
$('table.resizable').resizableColumns();

$(function() {
  $('table.resizable').resizableColumns();
})
body {
  margin: 0px;
}

table {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>
<table class="resizable" border="true">
  <thead>
  <tr>
    <th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>
    </tr>
    <tr>
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>
    </tr>
  </tbody>
</table>

I have tried several solutions today, the one working best for me is Jo-Geek/jQuery-ResizableColumns. Is is very simple, yet it handles tables placed in flex containers, which many of the other ones fail with.

<table class="resizable">
</table>
$('table.resizable').resizableColumns();

$(function() {
  $('table.resizable').resizableColumns();
})
body {
  margin: 0px;
}

table {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://jo-geek.github.io/jQuery-ResizableColumns/demo/resizableColumns.min.js"></script>
<table class="resizable" border="true">
  <thead>
  <tr>
    <th>col 1</th><th>col 2</th><th>col 3</th><th>col 4</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>
    </tr>
    <tr>
      <td>Column 1</td><td>Column 2</td><td>Column 3</td><td>Column 4</td>
    </tr>
  </tbody>
</table>

淤浪 2024-11-17 03:52:07

我已经完成了自己的 jquery ui 小部件,只是想它是否足够好。

I've done my own jquery ui widget, just thinking if it's good enough.

https://github.com/OnekO/colresizable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文