How to manipulate the position of a div

Asked

Viewed 3,536 times

4

I need to manipulate the position of two <div> in opposite motions.

I have researched many places but found no explanation of how such an effect can be done nor means of how to do it.

I didn’t want to ask for the answer, but I don’t even know how to research it!

  • 2

    Explain more about what you’re trying to do! You’re looking to animate the Divs in opposite directions?

  • var i=-1; var u=1; Function mover(op){ if(op=='left'){ Document.getElementById("div03").style.left=i+"px"; i-; } if(op=='right'){ Document.getElementById("div03").style.left=i+"px"; i++; } if(op=='low'){Document.getElementById("div03").style.top=u+"px"; u++ } if(op=='up'){ Document.getElementById("div03").style.top=u+"px"; u-; } }

1 answer

5

I won’t give you the answer of how to move two Divs in opposite directions, but here’s the basics of how to manipulate an HTML element.

Consider this div:

<div id="minhaDiv"></div>

In Javascript, you need:

// 1. Acesso ao objeto do DOM que representa a div
var div = document.getElementById('minhaDiv');

// 2. Manipular o objeto *style* da div para alterar sua aparência (incluindo posição)

// 2.1 Aparência
div.style.width = '50px';
div.style.height = '50px';
div.style.backgroundColor = '#ff0000';

// 2.2 Posição
div.style.position = 'absolute';
div.style.top = '100px';
div.style.left = '50px';

// 3. Pegadinha! Atenção ao alterar a posição baseada na atual:
var leftAtual = parseInt(div.style.left, 10);
div.style.left = (leftAtual + 5) + 'px'; // desloca 5px para a direita

To animate the position, you will need to handle one of these 3 functions:

  • 1

    +1. Complementing the "prank": also remember to use the right unit (if you were in px, set as px, if he was in em set as em etc). Or make the conversion from one to the other. (P.S. Or I’m wrong, and the value of the style is always in px?)

  • Okay. I think I get it! Thank you so much for your help. It was great Evaluates!

  • @mgibsonbr Good question, I will test later. But I think the unit varies even.

  • 1

    Apparently he converts... That’s why I like jQuery, with pure JS a simple little thing takes a lot of work, and is full of edge cases: for example, if the previous style is computed, read the value style will bring no result. Aff

  • In case using Jquery is simpler?

  • 1

    The unity varies yes (I did the previous example in a hurry, now that I came back I realized the error...). @Joãopedro the question is whether initially your element was positioned using a stylesheet, the attribute style will be empty (as the example above demonstrated), it is necessary to use getComputedStyle to get the correct value. With jQuery, it is simply .css(atr) to read and .css(atr, valor) to write, and the conversion to number and to px is made automatically (example).

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.