javascript 在javascript中动态增加div的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20439916/
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
dynamically increasing height of div in javascript
提问by Parminder
I want to increase the height of the div tag on click of button. Every time a user clicks a button it should increase the height of that particular div tag, say by 200px or so..
我想在单击按钮时增加 div 标签的高度。每次用户点击一个按钮时,它应该增加那个特定 div 标签的高度,比如 200px 左右。
HTML
HTML
<div id="controls">
<input type="button" onclick="incHeight()" id="btn" name="btn">
</div>
<div id="container" style="min-height:250px;"> </div>
The below script works properly
下面的脚本正常工作
Javascript
Javascript
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height = 250+'px';
}
</script>
But I want to do something like this, which is not working. The problem I think is the 'px' portion in the value. Anybody have any idea how to extract the INT portion of the value...
但我想做这样的事情,这是行不通的。我认为的问题是值中的“px”部分。任何人都知道如何提取值的 INT 部分......
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height += 250;
}
</script>
The problem is how do I get the '250' portion of the height value neglecting the 'px' in javascript..
问题是我如何获得高度值的 '250' 部分而忽略 javascript 中的 'px' ..
回答by Sergio
回答by Powerslave
Try something like
尝试类似
var container = document.getElementById('container');
container.style.height = (container.offsetHeight + 250) + "px";
In case offsetHeight
is not working, try parsing the style.height
for its numeric value instead.
如果offsetHeight
不起作用,请尝试解析style.height
其数值。
var currentHeight = (container.style.height) ? (parseInt(container.style.height.match(/[0-9]+/)[0]) : container.offsetHeight;
Also, simply parseInt(container.style.height)
might work
另外,parseInt(container.style.height)
可能会起作用
回答by GolezTrol
You can use a regular expression to only keep the numbers in the string:
您可以使用正则表达式只保留字符串中的数字:
var style = document.getElementById("container").style;
style.height = style.height.replace( /^\D+/g, '') + 'px';
回答by Mr.G
Try this:
试试这个:
getElementById('container').setAttribute("style","height:500px");
or
或者
function resize(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}