Java Reference
In-Depth Information
<style>
#divAdvert {
position: absolute;
font: 12px Arial;
top: 4px;
left: 0px;
}
</style>
</head>
<body>
<div id="divAdvert">
Here is an advertisement.
</div>
<script>
var direction = 2;
function doAnimation() {
var divAdvert = document.getElementById("divAdvert");
var currentLeft = divAdvert.offsetLeft;
if (currentLeft > 400 ││ currentLeft < 0) {
direction = -direction;
}
var newLocation = currentLeft + direction;
divAdvert.style.left = newLocation + "px";
}
setInterval(doAnimation, 10);
</script>
</body>
</html>
Save this as ch9 _ question2.html .
This modification sounds complex at first, but it actually simplifies the doAnimation() function
because one variable is responsible for:
the amount of pixels moved
the direction the element is moved
First, you remove the switchDirection variable and create a new one called direction , initializing
it with the value of 2 :
var direction = 2;
Then inside the doAnimation() function, you change the value of direction when the <div/>
element reaches one of its bounds (0 pixels or 400 pixels):
if (currentLeft > 400 ││ currentLeft < 0) {
direction = -direction;
}
Search WWH ::




Custom Search