Javascript 绝对定位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4814997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Absolute Positioning
提问by Mike Poole
I am trying to create a new div layer using JavaScript that can be absolutely positioned on the page after page load.
我正在尝试使用 JavaScript 创建一个新的 div 层,该层可以在页面加载后绝对定位在页面上。
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';
myLayer.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?
我遇到的问题是 div 位于原始正文内容之后,而不是放在新图层上。我该如何补救?
回答by Arnaud Le Blanc
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).
它不起作用的原因是您使用了x
and y
css 属性(不存在)而不是left
and top
。此外,对于左、上、宽、高,您必须指定一个单位(例如px
,像素)。
回答by leebriggs
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.
- 使用 top 和 left 而不是 x 和 y 设置位置。
- 绝对定位元素需要包含在也具有位置样式的东西中。通常的技巧是创建一个带有位置的容器:相对。
- 您应该使用 + 'px' 设置宽度、高度、顶部、左侧等样式。
- 您不需要为 div 设置 display: block 因为它已经是一个块元素。