|
Animating
Elements
In
the past, you may have used the following methods to move an existing
element to a new position in the document:
In
Netscape 4.x:
document.layers["sampleDiv"].moveTo(x,
y);
In
IE:
document.all["sampleDiv"].style.pixelLeft
= x;
document.all["sampleDiv"].style.pixelTop = y;
This
split in code is no longer necessary with NS6. Assign the new x
and y values directly
to the left and top
properties of an element's style object to reposition the element.
For example, the following code moves the sampleDiv layer to a new
position 200 pixels from the left edge of the document and 340 pixels
from the top edge:
var myElement
= document.getElementById("sampleDiv");
myElement.style.left = "200px";
myElement.style.top = "340px";
Again,
note the use of strings and the "px" suffix.
To
shift a layer's position relative to its current position, you must
first extract the left
and top values and
convert them into integers. You can do this with the JavaScript
parseInt method:
var myElement
= document.getElementById("sampleDiv");
var x = parseInt(myElement.style.left);
var y = parseInt(myElement.style.top);
Now
all you have to do is increment x
and y and reassign
them to the layer's left
and top properties:
x = x + 10;
y = y + 10;
myElement.style.left = x + "px";
myElement.style.top = y + "px";
With
a little optimization you can create your own custom methods that
take the ID of the layer element you want to move, and the horizontal
and vertical values as arguments:
function MoveLayerTo
(id,posX,posY){
// moves layer directly to new position
var myElement = document.getElementById(id);
myElement.style.left = posX + "px";
myElement.style.top = posY + "px";
}
function MoveLayerBy (id,incX,incY) {
// moves layer by increments
var myElement = document.getElementById(id);
myElement.style.left = parseInt(myElement.style.left)
+ incX + "px";
myElement.style.top = parseInt(myElement.style.top)
+ incY + "px";
}
Example:
Basic Animation Demo
|
Compatibility
note:
While
it's possible to use other units of measurement besides pixels,
such as points or em's, units other than pixels may be interpreted
differently in different browsers or on different platforms.
What a PC-compatible regards as "one point" is entirely
different than the same measurement displayed on a Mac. Pixels
are the safest way to ensure your positioning is consistent.
|
You've
seen the fundamentals of writing DHTML for Netscape 6. In Part II,
you'll see how to resize and clip a <DIV>
dynamically, change its color, background image, and manipulate
other properties with script.
Discuss
this article in the web.dhtml.scripting
discussion group!
Scott Andrew LePera LePera is a UI Developer at 2Bridge
Software in San Francisco, where he specializes in DHTML interface
components. You can read his musings on DHTML, standards and the
state of the Web at his site, www.scottandrew.com. Contact
him at scott@scottandrew.com.
Send comments to feedback@devx.com.
|