javascript如何通过em单位增加高度 [英] javascript how to increase height by em units

查看:42
本文介绍了javascript如何通过em单位增加高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I increase the height of an html element, by a certain number of em units, using JavaScript?

这是一个不起作用的示例,但演示了我正在尝试做的事情.在html页面的正文中:

Here's an example that doesn't work, but demonstrates what I'm trying to do. In the body of an html page:

<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单位,而不是像素.

I want to increase by em units, not pixels.

推荐答案

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

Get the computed style and use calc to sum:

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单位增加高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆