JavaScript 绝对定位
我正在尝试使用 JavaScript 创建一个新的 div 层,该层可以在页面加载后绝对定位在页面上。
我的代码如下:
<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>
页面可以在这里看到。
我遇到的问题是 div 位于原始正文内容之后,而不是位于新图层上。我该如何补救?
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';
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用此方法:
它不起作用的原因是您使用了
x
和y
css 属性(不存在)而不是left
和顶部
。另外,对于左、上、宽、高,您必须指定一个单位(例如px
表示像素)。Try with this instead:
The reason it was not working is that you used
x
andy
css properties (which don't exist) instead ofleft
andtop
. Also, for left, top, width, height you had to specify a unit (e.g.px
for pixels).尝试这些,
Try these,