javascript 如何动态地将一个元素放置在另一个元素之上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5293578/
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
How do you dynamically position one element on top of another?
提问by Justin Meltzer
I'm dynamically appending some html with jQuery and I want to insert it directly on top of another element. How do I do this?
我正在使用 jQuery 动态附加一些 html,我想将它直接插入到另一个元素之上。我该怎么做呢?
this is the code in my application.js file:
这是我的 application.js 文件中的代码:
$(document).ready(function() {
$('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){
$("#video_div").append($("<img>", { src: oembed.thumbnail_url, width:200 }));
});
});
The image is being inserted dynamically, and I want it to be directly on top of this:
图像是动态插入的,我希望它直接在此之上:
<div id="video_div"><%= link_to 'video', @video.video_url, :class => 'oembed' %></div>
回答by fx_
This is more like a CSS question. You want to make sure the parent element (#video_div) is positioned relatively (position: relative) and the inserted element (the img) is positioned absolutely (position: absolute)
这更像是一个 CSS 问题。您要确保父元素 (#video_div) 相对定位(位置:相对)并且插入的元素(img)绝对定位(位置:绝对)
Hook it to the top left, make sure they're the same size and you're golden.
把它挂在左上角,确保它们的大小相同,而且你是金色的。
#video_div {
position: relative;
width: 300px;
height: 300px;
}
#video_div img {
position: absolute;
top: 0px;
left: 0px;
width: 300px;
height: 300px;
}
回答by Christian Mann
Assuming you mean directly on top of it (obscuring it) in the z-order, a combination of JQuery's .position()method and absolute positioning should do the trick.
假设您的意思是直接在 z 顺序的顶部(将其遮住),JQuery 的.position()方法和绝对定位的组合应该可以解决问题。
$('<div>New Element</div>').css({
"position" : "absolute",
"left" : $foo.position().left,
"top" : $foo.position().top
}).appendTo($container);
Note: $containermust contain both the dynamically generated element and the target element.
注意:$container必须同时包含动态生成的元素和目标元素。

