jQuery 如何在表格行上使用 slideDown(或显示)功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/467336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:11:56  来源:igfitidea点击:

How to Use slideDown (or show) function on a table row?

jqueryanimationhtml-tableslidedown

提问by Greg

I'm trying to add a row to a table and have that row slide into view, however the slidedown function seems to be adding a display:block style to the table row which messes up the layout.

我正在尝试向表格中添加一行并将该行滑入视图,但是向下滑动功能似乎正在向表格行添加 display:block 样式,这会弄乱布局。

Any ideas how to work around this?

任何想法如何解决这个问题?

Here's the code:

这是代码:

$.get('/some_url', 
  { 'val1': id },

  function (data) {
    var row = $('#detailed_edit_row');
    row.hide();
    row.html(data);
    row.slideDown(1000);
  }
);

回答by Emily

Animations are not supported on table rows.

表格行不支持动画。

From "Learning jQuery" by Chaffer and Swedberg

来自 Chaffer 和 Swedberg 的“Learning jQuery”



Table rows present particular obstacles to animation, since browsers use different values (table-row and block) for their visible display property. The .hide() and .show() methods, without animation, are always safe to use with table rows. As of jQuery version 1.1.3, .fadeIn() and .fadeOut() can be used as well.

表格行给动画带来了特殊的障碍,因为浏览器为其可见显示属性使用不同的值(表格行和块)。没有动画的 .hide() 和 .show() 方法对于表行使用总是安全的。从 jQuery 1.1.3 版本开始,也可以使用 .fadeIn() 和 .fadeOut()。



You can wrap your td contents in a div and use the slideDown on that. You need to decide if the animation is worth the extra markup.

您可以将 td 内容包装在 div 中并在其上使用 slideDown。您需要决定动画是否值得额外的标记。

回答by wiks

I simply wrap the tr dynamically then remove it once the slideUp/slideDown has complete. It's a pretty small overhead adding and removing one or a couple of tags and then removing them once the animation is complete, I don't see any visible lag at all doing it.

我只是将 tr 动态包装起来,然后在 slideUp/slideDown 完成后将其删除。添加和删​​除一个或几个标签,然后在动画完成后删除它们是一个非常小的开销,我根本看不到任何明显的延迟。

SlideUp:

向上滑动

$('#my_table > tbody > tr.my_row')
 .find('td')
 .wrapInner('<div style="display: block;" />')
 .parent()
 .find('td > div')
 .slideUp(700, function(){

  $(this).parent().parent().remove();

 });

SlideDown:

滑下:

$('#my_table > tbody > tr.my_row')
 .find('td')
 .wrapInner('<div style="display: none;" />')
 .parent()
 .find('td > div')
 .slideDown(700, function(){

  var $set = $(this);
  $set.replaceWith($set.contents());

 });

I have to pay tribute to fletchzone.com as I took his plugin and stripped it back to the above, cheers mate.

我必须向 fletchzone.com 致敬,因为我拿走了他的插件并将其剥离到上面,干杯伙计。

回答by Vinny

Here's a plug-in that I wrote up for this, it takes a little from Fletch's implementation, but mine is used solely to slide a row up or down (no inserting rows).

这是我为此编写的一个插件,它从 Fletch 的实现中获得了一些帮助,但我的仅用于向上或向下滑动一行(不插入行)。

(function($) {
var sR = {
    defaults: {
        slideSpeed: 400,
        easing: false,
        callback: false     
    },
    thisCallArgs: {
        slideSpeed: 400,
        easing: false,
        callback: false
    },
    methods: {
        up: function (arg1,arg2,arg3) {
            if(typeof arg1 == 'object') {
                for(p in arg1) {
                    sR.thisCallArgs.eval(p) = arg1[p];
                }
            }else if(typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')) {
                sR.thisCallArgs.slideSpeed = arg1;
            }else{
                sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
            }

            if(typeof arg2 == 'string'){
                sR.thisCallArgs.easing = arg2;
            }else if(typeof arg2 == 'function'){
                sR.thisCallArgs.callback = arg2;
            }else if(typeof arg2 == 'undefined') {
                sR.thisCallArgs.easing = sR.defaults.easing;    
            }
            if(typeof arg3 == 'function') {
                sR.thisCallArgs.callback = arg3;
            }else if(typeof arg3 == 'undefined' && typeof arg2 != 'function'){
                sR.thisCallArgs.callback = sR.defaults.callback;    
            }
            var $cells = $(this).find('td');
            $cells.wrapInner('<div class="slideRowUp" />');
            var currentPadding = $cells.css('padding');
            $cellContentWrappers = $(this).find('.slideRowUp');
            $cellContentWrappers.slideUp(sR.thisCallArgs.slideSpeed,sR.thisCallArgs.easing).parent().animate({
                                                                                                                paddingTop: '0px',
                                                                                                                paddingBottom: '0px'},{
                                                                                                                complete: function () {
                                                                                                                    $(this).children('.slideRowUp').replaceWith($(this).children('.slideRowUp').contents());
                                                                                                                    $(this).parent().css({'display':'none'});
                                                                                                                    $(this).css({'padding': currentPadding});
                                                                                                                }});
            var wait = setInterval(function () {
                if($cellContentWrappers.is(':animated') === false) {
                    clearInterval(wait);
                    if(typeof sR.thisCallArgs.callback == 'function') {
                        sR.thisCallArgs.callback.call(this);
                    }
                }
            }, 100);                                                                                                    
            return $(this);
        },
        down: function (arg1,arg2,arg3) {
            if(typeof arg1 == 'object') {
                for(p in arg1) {
                    sR.thisCallArgs.eval(p) = arg1[p];
                }
            }else if(typeof arg1 != 'undefined' && (typeof arg1 == 'number' || arg1 == 'slow' || arg1 == 'fast')) {
                sR.thisCallArgs.slideSpeed = arg1;
            }else{
                sR.thisCallArgs.slideSpeed = sR.defaults.slideSpeed;
            }

            if(typeof arg2 == 'string'){
                sR.thisCallArgs.easing = arg2;
            }else if(typeof arg2 == 'function'){
                sR.thisCallArgs.callback = arg2;
            }else if(typeof arg2 == 'undefined') {
                sR.thisCallArgs.easing = sR.defaults.easing;    
            }
            if(typeof arg3 == 'function') {
                sR.thisCallArgs.callback = arg3;
            }else if(typeof arg3 == 'undefined' && typeof arg2 != 'function'){
                sR.thisCallArgs.callback = sR.defaults.callback;    
            }
            var $cells = $(this).find('td');
            $cells.wrapInner('<div class="slideRowDown" style="display:none;" />');
            $cellContentWrappers = $cells.find('.slideRowDown');
            $(this).show();
            $cellContentWrappers.slideDown(sR.thisCallArgs.slideSpeed, sR.thisCallArgs.easing, function() { $(this).replaceWith( $(this).contents()); });

            var wait = setInterval(function () {
                if($cellContentWrappers.is(':animated') === false) {
                    clearInterval(wait);
                    if(typeof sR.thisCallArgs.callback == 'function') {
                        sR.thisCallArgs.callback.call(this);
                    }
                }
            }, 100);
            return $(this);
        }
    }
};

$.fn.slideRow = function(method,arg1,arg2,arg3) {
    if(typeof method != 'undefined') {
        if(sR.methods[method]) {
            return sR.methods[method].apply(this, Array.prototype.slice.call(arguments,1));
        }
    }
};
})(jQuery);

Basic Usage:

基本用法:

$('#row_id').slideRow('down');
$('#row_id').slideRow('up');

Pass slide options as individual arguments:

将幻灯片选项作为单独的参数传递:

$('#row_id').slideRow('down', 500); //slide speed
$('#row_id').slideRow('down', 500, function() { alert('Row available'); }); // slide speed and callback function
$('#row_id').slideRow('down', 500, 'linear', function() { alert('Row available'); }); slide speed, easing option and callback function
$('#row_id').slideRow('down', {slideSpeed: 500, easing: 'linear', callback: function() { alert('Row available');} }); //options passed as object

Basically, for the slide down animation, the plug-in wraps the contents of the cells in DIVs, animates those, then removes them, and vice versa for the slide up (with some extra steps to get rid of the cell padding). It also returns the object you called it on, so you can chain methods like so:

基本上,对于向下滑动动画,插件将单元格的内容包装在 DIV 中,为它们设置动画,然后删除它们,反之亦然,用于向上滑动(通过一些额外的步骤来消除单元格填充)。它还返回您调用它的对象,因此您可以像这样链接方法:

$('#row_id').slideRow('down').css({'font-color':'#F00'}); //make the text in the row red

Hope this helps someone.

希望这可以帮助某人。

回答by Paolo Bergantino

You could try wrapping the contents of the row in a <span>and having your selector be $('#detailed_edit_row span');- a bit hackish, but I just tested it and it works. I also tried the table-rowsuggestion above and it didn't seem to work.

您可以尝试将行的内容包装在 a 中<span>并让您的选择器$('#detailed_edit_row span');- 有点hackish,但我刚刚测试了它并且它有效。我也尝试了table-row上面的建议,但似乎没有用。

update: I've been playing around with this problem, and from all indications jQuery needs the object it performs slideDown on to be a block element. So, no dice. I was able to conjure up a table where I used slideDown on a cell and it didn't affect the layout at all, so I am not sure how yours is set up. I think your only solution is to refactor the table in such a way that it's ok with that cell being a block, or just .show();the damn thing. Good luck.

更新:我一直在解决这个问题,从所有迹象来看,jQuery 需要它执行 slideDown 的对象是一个块元素。所以,没有骰子。我能够想象出一个表格,我在单元格上使用了 slideDown 并且它根本不影响布局,所以我不确定你的表格是如何设置的。我认为您唯一的解决方案是以这样的方式重构表格,即可以将该单元格作为一个块,或者只是.show();该死的东西。祝你好运。

回答by jaywiz

Select the contents of the row like this:

像这样选择行的内容:

$(row).contents().slideDown();

.contents()- Get the children of each element in the set of matched elements, including text and comment nodes.

.contents()- 获取匹配元素集中每个元素的子元素,包括文本和注释节点。

回答by jaywiz

I'm a bit behind the times on answering this, but I found a way to do it :)

我在回答这个问题上有点落后,但我找到了一种方法:)

function eventinfo(id) {
    tr = document.getElementById("ei"+id);
    div = document.getElementById("d"+id);
    if (tr.style.display == "none") {
        tr.style.display="table-row";
        $(div).slideDown('fast');
    } else {
        $(div).slideUp('fast');
        setTimeout(function(){tr.style.display="none";}, 200);
    }
}

I just put a div element inside the table data tags. when it is set visible, as the div expands, the whole row comes down. then tell it to fade back up (then timeout so you see the effect) before hiding the table row again :)

我只是在表格数据标签中放了一个 div 元素。当它设置为可见时,随着 div 的扩展,整行都会下降。然后告诉它在再次隐藏表格行之前淡出(然后超时以便您看到效果):)

Hope this helps someone!

希望这可以帮助某人!

回答by Stalin Gino

Have a table row with nested table:

有一个带有嵌套表的表行:

<tr class='dummyRow' style='display: none;'>
    <td>
        <table style='display: none;'>All row content inside here</table>
    </td>
</tr>


To slideDownthe row:

了slideDown行:

$('.dummyRow').show().find("table").slideDown();

Note:the row and it's content (here it is "table") both should be hiddenbefore animation starts.

注意:行和它的内容(这里是"table")都应该在动画开始之前隐藏



To slideUpthe row:

为了效果基本show行:

$('.dummyRow').find("table").slideUp('normal', function(){$('.dummyRow').hide();});

The second parameter (function()) is a callback.

第二个参数 ( function()) 是回调。



Simple!!

简单的!!

Note that there are also several optionsthat can be added as parameters of the slide up/down functions (the most common being durations of 'slow'and 'fast').

请注意,还有几个选项可以添加为上/下滑动功能的参数(最常见的是'slow'和 的持续时间'fast')。

回答by Johann

I've gotten around this by using the td elements in the row:

我通过使用行中的 td 元素解决了这个问题:

$(ui.item).children("td").effect("highlight", { color: "#4ca456" }, 1000);

Animating the row itself causes strange behaviour, mostly async animation problems.

动画行本身会导致奇怪的行为,主要是异步动画问题。

For the above code, I am highlighting a row that gets dragged and dropped around in the table to highlight that the update has succeeded. Hope this helps someone.

对于上面的代码,我突出显示了在表中拖放的一行,以突出显示更新已成功。希望这可以帮助某人。

回答by darkwind

I did use the ideas provided here and faced some problems. I fixed them all and have a smooth one-liner I'd like to share.

我确实使用了这里提供的想法并遇到了一些问题。我把它们都修好了,有一个光滑的单线,我想分享一下。

$('#row_to_slideup').find('> td').css({'height':'0px'}).wrapInner('<div style=\"display:block;\" />').parent().find('td > div').slideUp('slow', function() {$(this).parent().parent().remove();});

It uses css on the td element. It reduces the height to 0px. That way only the height of the content of the newly created div-wrapper inside of each td element matters.

它在 td 元素上使用 css。它将高度降低到 0px。这样,只有每个 td 元素内新创建的 div-wrapper 的内容高度才重要。

The slideUp is on slow. If you make it even slower you might realize some glitch. A small jump at the beginning. This is because of the mentioned css setting. But without those settings the row would not decrease in height. Only its content would.

SlideUp 运行缓慢。如果你让它更慢,你可能会意识到一些小故障。一开始的小跳跃。这是因为提到的 css 设置。但是如果没有这些设置,该行的高度不会降低。只有它的内容会。

At the end the tr element gets removed.

最后 tr 元素被删除。

The whole line only contains JQuery and no native Javascript.

整行只包含 JQuery 而没有原生 Javascript。

Hope it helps.

希望能帮助到你。

Here is an example code:

这是一个示例代码:

    <html>
            <head>
                    <script src="https://code.jquery.com/jquery-3.2.0.min.js">               </script>
            </head>
            <body>
                    <table>
                            <thead>
                                    <tr>
                                            <th>header_column 1</th>
                                            <th>header column 2</th>
                                    </tr>
                            </thead>
                            <tbody>
                                    <tr id="row1"><td>row 1 left</td><td>row 1 right</td></tr>
                                    <tr id="row2"><td>row 2 left</td><td>row 2 right</td></tr>
                                    <tr id="row3"><td>row 3 left</td><td>row 3 right</td></tr>
                                    <tr id="row4"><td>row 4 left</td><td>row 4 right</td></tr>
                            </tbody>
                    </table>
                    <script>
    setTimeout(function() {
    $('#row2').find('> td').css({'height':'0px'}).wrapInner('<div style=\"display:block;\" />').parent().find('td > div').slideUp('slow',         function() {$(this).parent().parent().remove();});
    }, 2000);
                    </script>
            </body>
    </html>

回答by Michael

I neded a table with hidden rows that slide in and out of view on row click.

我需要一个带有隐藏行的表格,这些行在行单击时滑入和滑出视图。

$('.tr-show-sub').click(function(e) {  
    var elOne = $(this);
    $('.tr-show-sub').each(function(key, value) {
        var elTwoe = $(this);
        
        if(elOne.get(0) !== elTwoe.get(0)) {
            if($(this).next('.tr-sub').hasClass('tr-sub-shown')) {
                elTwoe.next('.tr-sub').removeClass('tr-sub-shown');
                elTwoe.next('tr').find('td').find('div').slideUp();
                elTwoe.next('tr').find('td').slideUp();
            }
        }
        
        if(elOne.get(0) === elTwoe.get(0)) {
            if(elOne.next('.tr-sub').hasClass('tr-sub-shown')) {
                elOne.next('.tr-sub').removeClass('tr-sub-shown');
                elOne.next('tr').find('td').find('div').slideUp();
                elOne.next('tr').find('td').slideUp();
            } else {
                elOne.next('.tr-sub').addClass('tr-sub-shown');
                elOne.next('tr').find('td').slideDown();
                elOne.next('tr').find('td').find('div').slideDown();
            }
        }
    })
});
body {
        background: #eee;
    }
    
    .wrapper {
        margin: auto;
        width: 50%;
        padding: 10px;
        margin-top: 10%;
    }
    
    table {
        background: white;
        width: 100%;
    }
    
    table th {
        background: gray;
        text-align: left;
    }
    
    table th, td {
        border-bottom: 1px solid lightgray;
        padding: 5px;
    }
    
    table .tr-show-sub {
        background: #EAEAEA;
        cursor: pointer;
    }

    table .tr-sub td {
        display: none;
    }
    
    table .tr-sub td .div-sub {
        display: none;
    }
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<div class="wrapper">
    <table cellspacing="0" cellpadding="3">
        <thead>
            <tr class="table">
                <th>col 1</th>
                <th>col 2</th>
                <th>col 3</th>
            </tr>
        </thead>
        <tbody>
            <tr class="tr-show-sub">
                <td>col 1</td>
                <td>col 2</td>
                <td>col 3</td>
            </tr>
            <tr class="tr-sub">
                <td colspan="5"><div class="div-sub">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis auctor tortor sit amet sem tempus rhoncus. Etiam scelerisque ligula id ligula congue semper interdum in neque. Vestibulum condimentum id nibh ac pretium. Proin a dapibus nibh. Suspendisse quis elit volutpat, aliquet nisi et, rhoncus quam. Quisque nec ex quis diam tristique hendrerit. Nullam sagittis metus sem, placerat scelerisque dolor congue eu. Pellentesque ultricies purus turpis, convallis congue felis iaculis sed. Cras semper elementum nibh at semper. Suspendisse libero augue, auctor facilisis tincidunt eget, suscipit eu ligula. Nam in diam at ex facilisis tincidunt. Fusce erat enim, placerat ac massa facilisis, tempus aliquet metus. Fusce placerat nulla sed tristique tincidunt. Duis vulputate vestibulum libero, nec lobortis elit ornare vel. Mauris imperdiet nulla non suscipit cursus. Sed sed dui ac elit rutrum mollis sed sit amet lorem. 
                </div></td>
            </tr>
            <tr class="tr-show-sub">
                <td>col 1</td>
                <td>col 2</td>
                <td>col 3</td>
            </tr>
            <tr class="tr-sub">
                <td colspan="5"><div class="div-sub">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis auctor tortor sit amet sem tempus rhoncus. Etiam scelerisque ligula id ligula congue semper interdum in neque. Vestibulum condimentum id nibh ac pretium. Proin a dapibus nibh. Suspendisse quis elit volutpat, aliquet nisi et, rhoncus quam. Quisque nec ex quis diam tristique hendrerit. Nullam sagittis metus sem, placerat scelerisque dolor congue eu. Pellentesque ultricies purus turpis, convallis congue felis iaculis sed. Cras semper elementum nibh at semper. Suspendisse libero augue, auctor facilisis tincidunt eget, suscipit eu ligula. Nam in diam at ex facilisis tincidunt. Fusce erat enim, placerat ac massa facilisis, tempus aliquet metus. Fusce placerat nulla sed tristique tincidunt. Duis vulputate vestibulum libero, nec lobortis elit ornare vel. Mauris imperdiet nulla non suscipit cursus. Sed sed dui ac elit rutrum mollis sed sit amet lorem. 
                </div></td>
            </tr>
            <tr>
                <td>col 1</td>
                <td>col 2</td>
                <td>col 3</td>
            </tr>
        </tbody>
    </table>
</div>