使用jQuery动画line-height时出现奇怪的结果

3

我有一个表格有四行,想要用jQuery来动态改变它的行高。我使用以下代码来缩小并隐藏这些行:

$("table tr").animate({ 'line-height': 'hide' }, 5000);

但是,它并没有从当前行高开始缩小行高,而是先将它们变得非常巨大,然后再开始缩小。在此fiddle中按下隐藏按钮即可看到其效果: http://jsfiddle.net/YzCzd/1/

这在Chrome和Firefox中都会发生。

这是jQuery的一个bug吗?还是我做错了什么?


可能是因为hide不是一个有效的CSS属性,所以它不知道如何对其进行动画处理。http://www.w3schools.com/cssref/pr_dim_line-height.asp - Bogdan Rybak
1
这确实不是一个有效的 CSS 值,但 jQuery 可以理解它(以及 showtoggle),请参见 http://api.jquery.com/animate/。 - gpothier
1
我找到了一个解决方法,但这真的很hackish:强制jQuery不将行高视为数字属性。$.cssNumber['lineHeight'] = false; - gpothier
是的,我也刚注意到了...另一个解决方案就是只使用相对测量来设置行高。除非你不知道字体大小。 - Bogdan Rybak
1
已完成:http://bugs.jquery.com/ticket/13855 - gpothier
显示剩余3条评论
3个回答

2
回答我的问题:问题在于jQuery认为行高是一个无单位的属性,因此设置其值时没有单位,而浏览器将其解释为em。请参见https://github.com/jquery/api.jquery.com/issues/164 一种解决方法是强制jQuery将行高视为普通属性:
$.cssNumber['lineHeight'] = false;

0

Animate 只能使用值为数字的属性。

'line-height': 'hide'

我认为line-height没有名为hide的值。

查看这个


实际上,hideshowtoggle都是jQuery.animate的有效值,请参见http://api.jquery.com/animate/。 - gpothier
它们适用于 jQuery.animate,而不是 line-height CSS 属性。 - A. Cristian Nogueira

0
我用列表项修改了你的代码。 这是结果:http://jsfiddle.net/CtGmH/1/ CSS
    #table {
    width: 100%;
}

#table ul {
    height: 30px;
    background: green;
    list-style-type: none;
    padding: 0;
    margin: 10px;
}

#table ul.odd {
    background: red;
}
table li{position: relative; }

HTML

<div id="table">
    <ul class="odd"><li>A</li></ul>
    <ul><li>B</li></ul>
    <ul class="odd"><li>C</li></ul>
    <ul><li>E</li></ul>
</div>

<button onclick="window.show()">Show</button>
<button onclick="window.hide()">Hide</button>

JS

window.show = function() {
    $("ul").animate({ 'height': 30 }, 5000);
        $("ul li").css({'visibility':'visible'}).animate({ 'height': 30 }, 5000);
}

window.hide = function() {
    $("ul").animate({ 'height': 0 }, 5000);
    $("ul li").animate({ 'height': 0 }, 5000, function(){$("ul li").css({'visibility':'hidden'});});
}

你正在使用 height 属性,它确实有效。我的问题在于 line-height 属性(因为我需要使用表格)。 - gpothier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接