Javascript Absolute Positioning
I am trying to create a new div layer using JavaScript that can be absolutely positioned on the page after page load.
My code is as follows:
<html><head>
<script type="text/javascript">
function showLayer() {
var myLayer = document.createElement('div');
myLayer.id = 'bookingLayer';
myLayer.style.position = 'absolute';
myLaye开发者_开发知识库r.style.x = 10;
myLayer.style.y = 10;
myLayer.style.width = 300;
myLayer.style.height = 300;
myLayer.style.padding = '10px';
myLayer.style.background = '#00ff00';
myLayer.style.display = 'block';
myLayer.style.zIndex = 99;
myLayer.innerHTML = 'This is the layer created by the JavaScript.';
document.body.appendChild(myLayer);
}
</script>
</head><body bgcolor=red>This is the normal HTML content.
<script type="text/javascript">
showLayer();
</script>
</body></html>
The page can be seen here.
The problem I am having is that the div is sitting after the original body content rather than over it on a new layer. How can I remedy this?
Try with this instead:
var myLayer = document.createElement('div');
myLayer.id = 'bookingLayer';
myLayer.style.position = 'absolute';
myLayer.style.left = '10px';
myLayer.style.top = '10px';
myLayer.style.width = '300px';
myLayer.style.height = '300px';
myLayer.style.padding = '10px';
myLayer.style.background = '#00ff00';
myLayer.innerHTML = 'This is the layer created by the JavaScript.';
document.body.appendChild(myLayer);
The reason it was not working is that you used x
and y
css properties (which don't exist) instead of left
and top
. Also, for left, top, width, height you had to specify a unit (e.g. px
for pixels).
Try these,
- Set the position using top and left rather than x and y.
- An absolute positioned element needs to be contained inside something that also has a position style. The usual trick is to create a container with position: relative.
- You should be setting styles such as width, height, top, left etc with + 'px'.
- You don't need to set display: block for the div as it is already a block element.
精彩评论