如何使用 JavaScript 将 html 元素的高度增加一定数量的 em 单位?
这是一个不起作用的示例,但演示了我正在尝试做的事情。在 html 页面的正文中:
<textarea id="myTextArea" style="height:10em" onclick="test()"></textarea>
然后,在脚本中:
function test() {
// get the height, assign to var x
var x = document.getElementById("myTextArea").style.height;
// calculate height increase by 10 em
x += "10em";
// increase the height by amount calculated
document.getElementById("myTextArea").style.height = x;
}
我想增加 em 单位,而不是像素。
最佳答案
获取计算样式并使用calc
求和:
el.style.height = 'calc(' + getComputedStyle(el).height + ' + 10em)';
var el = document.querySelector('textarea');
document.querySelector('button').onclick = function() {
el.style.height = 'calc(' + getComputedStyle(el).height + ' + 1em)';
}
<button>Increase height</button><br />
<textarea style="height:10em"></textarea>
关于javascript 如何以 em 为单位增加高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33021935/