javascript如何通过em单位增加高度

时间:2015-10-08 17:05:57

标签: javascript html css

如何使用JavaScript增加一定数量的em单位的html元素的高度?

这是一个不起作用的例子,但展示了我尝试做的事情。在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单位,而不是像素。

3 个答案:

答案 0 :(得分:2)

获取计算出的样式并使用calc求和:

el.style.height = 'calc(' + getComputedStyle(el).height + ' + 10em)';

&#13;
&#13;
var el = document.querySelector('textarea');
document.querySelector('button').onclick = function() {
  el.style.height = 'calc(' + getComputedStyle(el).height + ' + 1em)';
}
&#13;
<button>Increase height</button><br />
<textarea style="height:10em"></textarea>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

当你拿回样式时,它是一个字符串,然后你添加另一个字符串,它就像

var x = "10em" + "10em";

x最终为10em10em,无效。你必须使用数字。

function test() {
    var x = document.getElementById("myTextArea").style.height;

    x = parseFloat( x.replace(/\D/g, '') );

    x += 10;

    document.getElementById("myTextArea").style.height = x + "em";
}

FIDDLE

答案 2 :(得分:0)

您需要在添加数字之前删除该单位,然后再次附加该单位:

function test() {
    // get the height, assign to var x
    var x = parseInt( document.getElementById("myTextArea").style.height );

    // calculate height increase by 10 em
    x += "10";

    // increase the height by amount calculated
    document.getElementById("myTextArea").style.height = x + "em";
}

请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt