How to get the height of the div, lease it to the multiple of 24 closest and apply the result in the div's own style?

6

I need a script that does just that: take the height of div , lease it to the nearest multiple of 24, and apply the result to style="height" of div itself.

It needs to be in pure Javascript, not Jquery.

Follow the structure of HTML

<div id="minhadiv">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id vulputate enim. Aenean venenatis magna non nisl elementum, a pellentesque metus semper. Integer porta diam consectetur, pretium odio sit amet, euismod urna. Quisque vel dui nec ligula iaculis malesuada et nec magna. Donec turpis nulla, viverra id sem nec, malesuada dictum leo.
</div>

The div has a height: auto , however it needs to be rounded up to multiples of 24 since the content is dynamic.

For example, if the content of div left it with 40px height, then the script should leave it with 48px height, which is the next multiple of 24 (24 * 2 = 48px ).

That would look like this:

<div id="minhadiv" style="height: 48px">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id vulputate enim. Aenean venenatis magna non nisl elementum, a pellentesque metus semper. Integer porta diam consectetur, pretium odio sit amet, euismod urna. Quisque vel dui nec ligula iaculis malesuada et nec magna. Donec turpis nulla, viverra id sem nec, malesuada dictum leo.
</div>

Now if the div was with 54px height, the script would also leave with 48px (depending on the rounding up to multiples of 24). In this case, div already has overflow: auto in the CSS file, since the content will exceed the size that the script defined.

    
asked by anonymous 06.09.2014 / 23:16

1 answer

4

You can use these two to get the height of div :

var alturaAtual = document.getElementById('teste').clientHeight;

or

var alturaAtual = document.getElementById('teste').offsetHeight;

The difference from offsetHeight to clientHeight is that it returns the height including padding , border and scrollbar . You should analyze which is best for your situation.

I'm not sure what you want but I did a function to change the height in multiples of 24.

HTML CODE

<!DOCTYPE html>
<html>
<head></head>
<body>
    <div id="teste" style="height: 65px;"></div>
</body>
</html>

SCRIPT [UPDATED]

function mudaAltura(idDiv) {
    var alturaAtual = document.getElementById(idDiv).offsetHeight;
    if (alturaAtual % 24 !== 0) {
        var resultado = parseInt(alturaAtual / 24);
        var novaAltura = 24 * (resultado + 1);
        document.getElementById('teste').style.height = novaAltura + "px";
    }
}

Then you call the function by setting the ID of the DIV as a parameter. Ex: mudaAltura("minhaid");

    
07.09.2014 / 00:31