Javascript 如何将高度添加到现有高度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8699956/
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-24 07:08:19  来源:igfitidea点击:

How to add height to existing height?

javascriptjquerycss

提问by whamsicore

For example I want to add 20pxto <div id='example'></div>, which is currently 20px.

例如,我想添加20px<div id='example'></div>,目前是20px.

I could get the existing height and add 20pxand input it as the new height, but I wish to learn if there is a better way that might work like a +=operator.

我可以获取现有高度并将其添加20px并输入为新高度,但我希望了解是否有更好的方法可以像+=操作员一样工作。

回答by andlrc

There are many ways to do it: http://jsperf.com/jquery-height-vs-css-height

有很多方法可以做到:http: //jsperf.com/jquery-height-vs-css-height

jsbin.com/utaduy

jsbin.com/utaduy

$('#example').css( "height", "+=20px" );


$('#example').height( $("#example").height() + 20 );

回答by Jasper

You can pass a function into height()that has the element's current height as an argument and the returnof the function will be the new height:

您可以将一个函数传递给以height()元素的当前高度作为参数return的函数,并且函数的 将是新的高度:

$('#example').height(function (index, height) {
    return (height + 20);
});

Here is a demo: http://jsfiddle.net/grajh/

这是一个演示:http: //jsfiddle.net/grajh/

Docs: http://api.jquery.com/height/

文档:http: //api.jquery.com/height/

回答by kaz

That way:

那样:

$('#example').height( $('#example').height() + 20 );