Java Reference
In-Depth Information
Positioning and Moving Content
Changing the appearance of an element is an important pattern in DHTML, and it fi nds its place in
many DHTML scripts. However, there is more to DHTML than just changing the way content appears
on the page; you can also change the position of an element with JavaScript.
Moving content with JavaScript is just as easy as using the style object. You use the position prop-
erty to change the type of position desired, and by using the left and top properties, you can position
the element.
var divAdvert = document.getElementById(“divAdvert”);
divAdvert.style.position = “absolute”;
divAdvert.style.left = “100px”; //Set the left position
divAdvert.style.top = “100px”; //Set the right position
This code fi rst retrieves the divAdvert element. Then it sets the element's position to absolute and
moves the element 100 pixels from the left and top edges. Notice the addition of px to the value
assigned to the positions. Many browsers require you to specify a unit when assigning a positional
value; otherwise, the browser will not position the element.
Note that positioning elements requires the position of absolute or relative.
Try It Out Moving an Element Around
Moving an element around on the page, as you've seen, is quite similar to changing other styles with
the style object. However, the ability to move an element on the page is used quite often, and you will
defi nitely see it later in the chapter. Therefore, you are going to build a page that enables you to specify
the location of an element through form fi elds.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 12: Example 6</title>
<style type=”text/css”>
#divBox
{
position: absolute;
background-color: silver;
width: 150px;
height: 150px;
}
input
{
width: 100px;
}
</style>
<script type=”text/javascript”>
function moveBox() {
var divBox = document.getElementById(“divBox”);
var inputLeft = document.getElementById(“inputLeft”);
Search WWH ::




Custom Search